如何将树转换为列表: 到目前为止,我有以下代码,但它提出了几个问题:
type 'a tree = Lf | Br of 'a * 'a tree * 'a tree;;
let rec elementRight xs = function
| LF ->false
| Br(m,t1,t2) -> if elementRight xs t1 = false then t1::xs else element xs t1;; //cannot find element
let rec elementLeft xs = function
| LF ->false
| Br(m,t1,t2) -> if elementLeft xs t2 = false then t2::xs else element xs t2 ;; //cannot find element
let rec element xs = function
| LF ->[]
| Br(m,t1,t2) -> xs::(elementRight xs t1)::(elementRight xs t2)::(elementLeft xs t1)::(elementLeft xs t2);;
答案 0 :(得分:1)
您的代码存在许多问题:
你不应该在行的末尾有;;
(我猜这意味着你要复制并粘贴到repl中,你应该使用fsx文件代替并使用“发送”复制“)。
这:| LF ->false
正在返回一个bool,而这个:| Br(m,t1,t2) -> if elementRight xs t1 = false then t1::xs else element xs t1
正在返回'a list
。表达式只能有一个类型,因此返回两个是编译错误。我猜你真正要做的是让叶子返回[]
,然后在你的分支案例中检查空列表是这样的:
let rec elementRight xs = function
| LF ->[]
| Br(m,t1,t2) -> if elementRight xs t1 = List.empty then t1::xs else element xs t1
3。当使用相互递归函数时,您需要对所有声明使用and
关键字,但第一个是这样的:
let rec elementRight xs = function
...
and elementLeft xs = function
...
and element xs = function
...