简体   繁体   中英

Haskell defining a tree

In haskell I can do things such as

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)

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.

In your tree , you are mixing data types ( Btree ) with constructors, while you should only be using constructors. 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) .

So to create your tree of depth 2 considering the above you write:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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