Ocaml 类型错误(变体/模式匹配)

问题描述 投票:0回答:1

尝试进行简单的模式匹配与变体,这将为我提供二叉树节点字符串的有序连接,但在递归实现中出现错误:

type btnode =
  | Leaf
  | Node of string * btnode * btnode


let rec inorder bt = function
  | Leaf -> ""
  | Node(s, left, right) -> 
    (inorder left) ^ s ^ (inorder right)
  
let tree = inorder Node("a", Node("b", Leaf, Leaf), Leaf)

错误:此表达式的类型为 btnode -> string 但需要一个字符串类型的表达式

pattern-matching ocaml variant
1个回答
0
投票

这个:

let tree = inorder Node ("a", Node ("b", Leaf, Leaf), Leaf)

解析为:

let tree = inorder (Node) ("a", Node ("b", Leaf, Leaf), Leaf)

您可能想要:

let tree = inorder (Node ("a", Node ("b", Leaf, Leaf), Leaf))

或者:

let tree = inorder @@ Node ("a", Node ("b", Leaf, Leaf), Leaf)

但是,您还在函数中引入了不必要的参数:

let rec inorder bt = function
  | Leaf -> ""
  | Node(s, left, right) -> 
    (inorder left) ^ s ^ (inorder right)

bt
参数从未使用过且不需要。

let rec inorder = function
  | Leaf -> ""
  | Node(s, left, right) -> 
    (inorder left) ^ s ^ (inorder right)
© www.soinside.com 2019 - 2024. All rights reserved.