简体   繁体   English

Haskell定义一棵树

[英]Haskell defining a tree

In haskell I can do things such as 在haskell中,我可以执行以下操作

a :: Int
a = 15

I have the datatype as below 我的数据类型如下

data Btree a = ND | Data a |  Branch (Btree a) (Btree a) deriving (Show, Eq)

How can I define a tree, not using a function, such as above. 如何定义树,而不使用上面的函数。

I have tried; 我努力了;

tree :: BTree
tree = Branch Btree (Branch ND Data 1) (Branch ND (Branch ND ND))

I cannot seem to get it to work (I am new to haskell so if this is very basic I apologise in advance) 我似乎无法使它正常工作(我是Haskell的新手,因此,如果这很基础,我会提前道歉)

Keep in mind that to construct an instance of the data type you need to call one of its constructor functions. 请记住,要构造数据类型的实例,您需要调用其构造函数之一。 All these constructors, ND , Data , Branch , are just regular functions, so you should call them as such. 所有这些构造函数NDDataBranch都是常规函数,因此应这样称呼它们。

In your tree , you are mixing data types ( Btree ) with constructors, while you should only be using constructors. tree ,您正在将数据类型( Btree )与构造函数混合,而您只应使用构造函数。 Also, keep in mind that the function call (the 'space operator' is left-associated) is very greedy, so Branch ND Data 1 calls the function Branch with 3 arguments, rather than what you want: Branch ND (Data 1) . 另外,请记住,函数调用(“空间运算符”是左关联的)非常贪婪,因此Branch ND Data 1使用3个参数而不是您想要的参数来调用函数BranchBranch ND (Data 1)

So to create your tree of depth 2 considering the above you write: 因此,考虑到以上内容,您可以创建深度为2的树:

tree = Branch (Branch ND (Data 1)) (Branch ND (Branch ND ND))

Note that Data 1 will be a Btree as well without any additional baggage 请注意, Data 1也将是Btree,无需额外负担

Prelude> :t (Data 1)
(Data 1) :: Num a => Btree a

if you want a simple branch with a right element only you can write 如果您只需要带有正确元素的简单分支,则可以编写

Branch ND (Data 1)

or two level deep as in the other answer. 或在另一个答案中深入两层。 At this point convenient constructor functions will be handy to minimize noise and typing. 此时,方便的构造函数将很方便,以最大程度地减少噪声和打字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM