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)
将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节中找到它.它被特别列为语言扩展.