Recently I started to learn about Haskell, and am struggling with the following exercise:
Write functions root :: Rose a -> a and children :: Rose a -> [Rose a] that return the value stored at the root of a rose tree, respectively the children of the root of a rose tree.
They gave me the following basic code to start:
data Rose a = a :> [Rose a] deriving (Eq, Show)
I don't know what (:>) means. I tried to understand it by typing in the ghci
Input: :t (:>)
Output: a -> [Rose a] -> Rose a
So I think it means that you have an a
value, which will be used to lookup Rose a
out of a list and returns Rose a
, but I'm still confused what to do next.
If I look at the signature of root :: Rose a -> a
, the function would look like this:
root (Rose a) = a
And the function of children :: Rose a -> [Rose a]
:
children (Rose a) = (Rose a):[]
This is not correct, and I don't how to make it correct.
The declaration
data Rose a = a :> [Rose a]
is basically equivalent to
data Rose a = Node a [Rose a]
In other words, Node
is a data structure containing a datum and a list of child nodes. But in the definition above, rather than calling it Node
, it's called :>
. It's just a made-up name; Haskell allows you to create user-defined operators like this.
If the name Node
was used, you could write
root (Node datum children) = datum
Or, more briefly,
root (Node a rs) = a
Since the name given is actually :>
, you'd have to write it as
root (a :> rs) = a
In particular, you seem to be trying to use Rose
, but that's the type constructor, not the value constructor. Similarly, you seem to be trying to use the ":
" operator, but that's for lists, not rose trees.
Hopefully that clears up some things for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With