【问题标题】:Convert tree to list将树转换为列表
【发布时间】:2014-06-19 14:24:12
【问题描述】:

如何将树转换为列表: 到目前为止,我有以下代码,但它给出了几个问题:

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);;

【问题讨论】:

  • 你能告诉我们什么问题吗?
  • 问题 1. 在 t2::xs 和 t1::xs 上,预期的表达式是 bool 并且有 'a list 2. on element xs t2 ;;找不到元素

标签: recursion tree f# f#-interactive


【解决方案1】:

你的代码有很多问题:

  1. 你不应该在行尾有;;(我猜这意味着你正在复制并粘贴到repl中,你应该真正使用fsx文件并使用“发送到repl ")。

  2. 这个:| LF ->false 返回一个布尔值,而这个:| 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
  ...

【讨论】:

  • elementBr 案例中,您似乎也有一个逻辑错误,但我会让您解决这个问题。
  • 提示:每个函数都返回一个列表,在两个列表上使用:: 会给你一个列表列表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多