【问题标题】:Record type pattern matching in OcamlOcaml 中的记录类型模式匹配
【发布时间】:2013-06-14 22:50:27
【问题描述】:

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

两大类定义如下:

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();;

但是,如果我有这样的状态:

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

然后当我调用函数时:

print_state initial_state;;

会有编译错误。任何人都可以说出编译失败的原因。感谢您的建议。

Error: Syntax error
unexpected token "("

【问题讨论】:

  • 但是为什么要对记录进行模式匹配?要从initial_state 中取出lcd,请使用initial_state.lcd

标签: types pattern-matching ocaml record


【解决方案1】:

记录模式看起来像记录:

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

【讨论】:

  • @yjasrc 在现代 OCaml 中,如果您以与标签相同的方式命名变量,也可以跳过 = 部分:match s with {lcd; vpr; _ } -> print_int lcd; print_int vpr
  • 添加到 luksatfi 的评论中,也根本不需要匹配声明。 let print_state {lcd; vpr; _} = ... 应该够了。
  • 我在谷歌搜索之前尝试了相反的方法 ({a = lcd...),这对我来说似乎更自然,但是嘿。至少一种方法。感谢您的回答,并感谢@yjasrc 提出问题。
  • 在我的例子中,我有一个 match 语句,因为它是一个结果类型。我不喜欢未命名的var,所以我更喜欢{lcd; vpr; lka = _lka; loa = _loa;}如果字段多的话可能会不一样,但是如果只有少数,阅读代码的时候看看还有什么可用的更有趣,即使字段当前未使用。
猜你喜欢
  • 1970-01-01
  • 2011-10-29
  • 2016-01-17
  • 1970-01-01
  • 2021-12-13
  • 2018-08-19
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多