在Ocaml中记录类型模式匹配

yja*_*src 15 ocaml types record pattern-matching

我正在尝试使用模式匹配来编写计算器应用程序.

两种主要类型定义如下:

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();;
Run Code Online (Sandbox Code Playgroud)

但是,如果我有一个像这样的州:

let initial_state = { lcd=0; lka=Equals; loa=Equals; vpr=0 } ;; 
Run Code Online (Sandbox Code Playgroud)

然后当我调用函数时:

print_state initial_state;;
Run Code Online (Sandbox Code Playgroud)

它会有编译错误.任何人都可以知道编译失败的原因是什么.谢谢你.

Error: Syntax error
unexpected token "("
Run Code Online (Sandbox Code Playgroud)

Jef*_*eld 31

记录模式看起来像一条记录:

match s with
| { lcd = a; vpr = d; _ } -> (* Expression *)
Run Code Online (Sandbox Code Playgroud)

  • @yjasrc在现代OCaml中,如果你以与标签相同的方式命名变量,你也可以跳过`=`部分:`match s with {lcd; VPR; _} - > print_int lcd; print_int vpr`. (6认同)
  • 要添加到 luksatfi 的评论中,也根本不需要有 match 语句。`让 print_state {lcd; 虚拟PR;_} = ...` 应该足够了。 (2认同)