something
something

Reputation: 107

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)

Upvotes: 0

Views: 118

Answers (2)

karakfa
karakfa

Reputation: 67567

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.

Upvotes: 2

MicroVirus
MicroVirus

Reputation: 5487

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

Upvotes: 3

Related Questions