Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Record type pattern matching in Ocaml

I'm trying to use pattern matching to write a calculator application.

Two major types defined as below:

type key = Plus | Minus | Multi | Div | Equals | Digit of int;;

type state = {
    lcd: int; (* last computation done *)
    lka: key; (* last key actived *)
    loa: key; (* last operation actived *)
    vpr: int (* value print on the screen *)
};;

let print_state s =
    match s with
     state (a,_,_,d) -> print_int a; //Here has the compile error
                print_newline();
                print_int d;
                    print_newline();;

However, if I have a state like:

let initial_state = { lcd=0; lka=Equals; loa=Equals; vpr=0 } ;; 

Then when I invoke the function:

print_state initial_state;;

It will have the compile error. Anyone can tell what's the reason for unsuccessful compilation. Thanks in adv.

Error: Syntax error
unexpected token "("
like image 752
yjasrc Avatar asked Jun 18 '13 16:06

yjasrc


People also ask

How does pattern matching work in OCaml?

Pattern matching comes up in several places in OCaml: as a powerful control structure combining a multi-armed conditional, unification, data destructuring and variable binding; as a shortcut way of defining functions by case analysis; and as a way of handling exceptions.

What is a record in OCaml?

A record represents a collection of values stored together as one, where each component is identified by a different field name.

What does :: do in OCaml?

Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ).

What is pattern matching syntax?

The pattern-matching algorithm uses a variety of techniques to match different kinds of expression. Data elements such as numbers, strings, booleans are matched by comparison: a pattern consisting of a single data element matches only that exact element.


1 Answers

A record pattern looks like a record:

match s with
| { lcd = a; vpr = d; _ } -> (* Expression *)
like image 58
Jeffrey Scofield Avatar answered Nov 02 '22 20:11

Jeffrey Scofield