2017-10-05 72 views
0

我有以下的数据类型(请忽略了一个事实,这可能是方式更简单)如何在OCaml中模式匹配记录?

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键;(...)})

+0

你或许应该一分为二的匹配表达式,从而使第一个只涉及王氏的'Null'和'Pos'标签,第二个用于'Pos'情况下的*参考值*,而不是匹配整个'ref'。 – didierc

回答

4

来匹配的引用代替

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

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

不幸的是,这将使得代码更密集:-)

3

我认为这个问题是您尝试模式匹配与ref,这实在是对含有记录只是糖可变的contents字段`。

尝试

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