将树转换为列表 [英] Convert tree to list

查看:77
本文介绍了将树转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I convert a tree to a list: So far I have the following code but its giving several issues:

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

推荐答案

您的代码存在许多问题:

There are a number of problems with your code:

  1. 您不应该在行尾使用;;(我猜这意味着您要复制并粘贴到repl中,您应该真正使用fsx文件,而应使用"send to repl ).

  1. You shouldn't have ;; at the end of lines (I'm guessing this means you're copy and pasting into the repl, you should really use an fsx file instead and use "send to repl").

此:| LF ->false返回布尔值,而此:| Br(m,t1,t2) -> if elementRight xs t1 = false then t1::xs else element xs t1返回'a list.一个表达式只能有一种类型,因此返回两种是编译错误.我猜你真正的意思是让叶子返回[],然后在分支情况下检查空列表,如下所示:

This: | LF ->false is returning a bool, while this: | Br(m,t1,t2) -> if elementRight xs t1 = false then t1::xs else element xs t1 is returning an 'a list. An expression can only have one type, so returning two is a compile error. I'm guessing what you really are meaning to do is have the leaf return [] and then check for empty list in your branch case something like this:

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关键字,但第一个是这样的:

3 . when using mutually recursive functions you need to use the and keyword for all declarations but the first like this:

let rec elementRight xs = function
  ...
and elementLeft xs = function
  ...
and element xs = function
  ...

这篇关于将树转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆