我有这个:
type 'a queue = {f : 'a stream; lenf : int; r : 'a stream; lenr : int};;
let empty :'a queue = {f = Nil; lenf = 0; r = Nil; lenr = 0};;
let is_empty (q :'a queue) =
match q with
| {Nil; _; Nil; _} -> true
| {_; _; _; _} -> false;;
但它不编译。
{Nil; _; Nil; _}
有什么问题吗?
记录的字段按名称访问,而不是按顺序访问。所以你需要在记录模式中给出字段名称。
# let is_empty (q : 'a queue) =
match q with
| { f = Nil; lenf = _; r = Nil; lenr = _ } -> true
| _ -> false
;;
val is_empty : 'a queue -> bool = <fun>
如果你不关心它们,你可以省略字段,即,如果它们可以匹配任何东西。对于未完全指定的记录模式,存在警告(警告 9)。如果包含尾随的
_
,即使警告9 生效,编译器也不会警告您某些字段未指定:
# let is_empty (q : 'a queue) =
match q with
| { f = Nil; r = Nil; _ } -> true
| _ -> false
;;
val is_empty : 'a queue -> bool = <fun>
或者,您可以简单地访问相关的记录字段并使用布尔表达式。
# let is_empty (q : 'a queue) =
q.f = Nil && q.r = Nil;;
val is_empty : 'a queue -> bool = <fun>
match
表达式是一个很棒的工具,但它并不是 OCaml 中唯一的工具。使用最好的工具来完成工作。