Nac*_*ott 1 ocaml records match
我有一个类型记录:
type record = { first : string; second : string list; third : string }
Run Code Online (Sandbox Code Playgroud)
我想用匹配从中提取数据......我该怎么做?
请告诉我.谢谢!
小智 6
您可以匹配整个记录:
match my_record with
| { first = "something"; } -> do_something
| { second = hd :: tl; third = "something else"; } -> do_something_else
(* ... *)
Run Code Online (Sandbox Code Playgroud)
或使用点表示法在其中定位特定字段:
match my_record.second with
| hd :: tl -> do_something
(* ... *)
Run Code Online (Sandbox Code Playgroud)
也可以使用称为字段punning的句法快捷方式对函数中的记录进行构造:
let fun_example { first; third; _ } =
"This is first: " ^ first ^ " and this is third: " ^ third
Run Code Online (Sandbox Code Playgroud)
或者通过为字段提供别名:
let fun_example_2 { first = f; third = t; _ } =
"This is first: " ^ f ^ " and this is third: " ^ t
Run Code Online (Sandbox Code Playgroud)
; _模式中的下划线用于告诉编译器,当#warnings "+9"在顶层中打开指令时,它不应该担心不完整的匹配.根据您的风格,可能会省略.
有关更复杂的细节,请参阅RWO,有一个关于记录的伟大章节!