【问题标题】:How to pattern match records in OCaml?如何在 OCaml 中对记录进行模式匹配?
【发布时间】:2018-03-16 12:32:43
【问题描述】:

我有以下数据类型(请忽略这可能更简单的事实)

type tKey = Key of int;;

type tBST = Null | Pos of node ref
        and node = {mutable key : tKey; 
            mutable left : tBST; 
            mutable right : tBST};;

此函数出现以下错误,看起来我的模式匹配不正确

let rec string_of_tree = function
    Null -> "()"
    | Pos (ref {key; left = Null; right = Null}) -> Printf.sprintf "(%s)" (string_of_root (root tree))
    | Pos (ref {key; left; right}) -> Printf.sprintf "(%s %s %s)" 
                            (string_of_root (root tree)) 
                            (string_of_tree (leftLeaf tree)) 
                            (string_of_tree (rightLeaf tree));;

Error: Syntax error: ')' expected
Error: This '(' might be unmatched

错误指的是以下括号:(ref {key; ( ... )})

【问题讨论】:

  • 您可能应该将匹配表达式一分为二,这样第一个只处理NullPos 标签,第二个处理引用值 i> 在Pos 的情况下,而不是匹配整个ref

标签: pattern-matching ocaml record


【解决方案1】:

要匹配引用,您不能使用refref 不是构造函数,它实际上只是一个引用的函数。要匹配参考,您可以使用{ contents = ... }

不幸的是,这会使代码更加密集:-)

【讨论】:

    【解决方案2】:

    我认为问题在于您尝试与 ref 进行模式匹配,这实际上只是包含可变 contentsfield 的记录的糖。

    尝试替换

    | Pos (ref { ... }) -> ...
    

    | Pos { contents = { ... }} -> ...
    

    【讨论】:

      猜你喜欢
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      相关资源
      最近更新 更多