Record type pattern matching in Ocaml

yjasrc picture yjasrc · Jun 18, 2013 · Viewed 11.4k times · Source

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 "("

Answer

Jeffrey Scofield picture Jeffrey Scofield · Jun 18, 2013

A record pattern looks like a record:

match s with
| { lcd = a; vpr = d; _ } -> (* Expression *)