Bar
Bar

Reputation: 83

Tree data doesn't compile in haskell

data Node = Blue | Green | Red
data Tree = Leaf Node | Node [Tree]

main = do
  let a = Blue[Leaf Red]
  print 1

It gives me the following error:

main.hs:5:15: error:
• Couldn't match expected type ‘[Tree] -> t’
              with actual type ‘Node’
• The function ‘Blue’ is applied to one argument,
  but its type ‘Node’ has none
  In the expression: Blue [Leaf Red]
  In an equation for ‘a’: a = Blue [Leaf Red]
• Relevant bindings include a :: t (bound at main.hs:5:11)

And I don't understand why it says it got Node instead of [Tree]

Upvotes: 1

Views: 114

Answers (1)

mschmidt
mschmidt

Reputation: 2800

You can create a Tree as a single leaf with one of the colors, e.g. Leaf Red or as a node with a list of other trees, e.g. Node [Leaf Red]. Your main function should look like this:

main = do
  let a = Node [Leaf Red]
  print 1

Or:

main = do
  let a = Node [Leaf Blue, Leaf Red]
  print 1

In case you also want to add colors to your nodes, you can redefine your Tree datatype to:

data Tree = Leaf Node | Node Node [Tree]
...
let a = Node Blue [Leaf Red]

Reading this may be confusing, so you should consider renaming either the Node type or the Node data constructor.

Upvotes: 6

Related Questions