尝试进行简单的模式匹配与变体,这将为我提供二叉树节点字符串的有序连接,但在递归实现中出现错误:
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 但需要一个字符串类型的表达式
这个:
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)