记录模式匹配

MiP*_*MiP 3 f# ocaml functional-programming record pattern-matching

根据这个被接受的答案,在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 -> ()
    | [] -> ()
Run Code Online (Sandbox Code Playgroud)

Jef*_*eld 7

将OCaml和F#视为同一种语言可能没有帮助.您的代码无效OCaml有几个原因.

但是你是对的,_在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>
Run Code Online (Sandbox Code Playgroud)

很难找到这方面的文档.您可以在OCaml手册的第7.7节中找到它.它被特别列为语言扩展.