记录模式匹配

时间:2017-05-14 06:24:44

标签: f# functional-programming pattern-matching ocaml record

根据这个accepted answer,在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 个答案:

答案 0 :(得分: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>

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

相关问题