【问题标题】:Record pattern matching记录模式匹配
【发布时间】:2017-05-14 06:24:43
【问题描述】:

根据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 -> ()
    | [] -> ()

【问题讨论】:

  • 也许这只是 OCaml 和 F# 之间的不兼容。出于好奇,您是如何得出它应该在 F# 中工作的结论的? (我并不是说不兼容是一件好事;只是说它可能是一件事)。

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


【解决方案1】:

将 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 中找到它。它被专门列为语言扩展。

【讨论】:

    猜你喜欢
    • 2016-10-29
    • 2011-10-29
    • 2013-10-19
    • 2013-06-25
    • 2018-01-08
    • 1970-01-01
    • 2021-09-14
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多