记录模式匹配

3
根据这个被接受的答案,在F#和OCaml中,我需要使用下划线来丢弃记录中其余的部分。但是,为什么handle'函数可行而handle函数不行?
type Type = Type of int

type Entity =
    { type' : Type
      foo : string }

let handle entities =
    match entities with
    | {type' = Type i; _ }::entites -> ()
    | [] -> ()

let handle' entities =
    match entities with
    | {type' = Type i }::entites -> ()
    | [] -> ()

1
也许这只是OCaml和F#之间的不兼容性问题。出于好奇,你是怎么得出它应该在F#中工作的结论的?(我并不是说不兼容性是一件好事;只是可能存在这种情况)。 - Robert Nielsen
1个回答

7

将OCaml和F#视为同一种语言可能不是很有帮助。您的代码在多个方面上都无效。

但是您是对的,在OCaml中,_是不必要的。如果您想获得关于不完整记录模式的警告,则使用_标记有意不完整的记录模式,并打开警告9,然后如果没有指定记录的所有字段,则没有_的记录模式将被标记。

$ rlwrap ocaml -w +9
        OCaml version 4.03.0

# type t = { a: int; b: string};;
type t = { a : int; b : string; }
# let f {a = n} = n;;
Warning 9: the following labels are not bound in this record pattern:
b
Either bind these labels explicitly or add '; _' to the pattern.
val f : t -> int = <fun>

这个文档相对较难找到。您可以在OCaml手册的第7.7节中找到它,它被列为一种语言扩展。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接