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 "("
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.
A record represents a collection of values stored together as one, where each component is identified by a different field name.
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] ).
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.
A record pattern looks like a record:
match s with
| { lcd = a; vpr = d; _ } -> (* Expression *)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With