Get the root of a rose tree in Haskell

I recently started learning 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:

data Rose a = a:> [Rose a]
    deriving (Eq, Show)

I don't know what (:>) means. I tried to figure it out by typing ghci

Input: :t (:>)
Output: a -> [Rose a] -> Rose a

      

So, I guess this means you have a value a

to be used to search Rose a

from the list and return Rose a

, but I'm still confused as to what to do next.

If I look at the signature root :: Rose a -> a

, the function looks like this:

root (Rose a) = a 

      

And the function children :: Rose a -> [Rose a]

:

children (Rose a) = (Rose a):[]

      

This is not correct and I don't understand how to do it.

+3


source to share


1 answer


Ad

data Rose a = a :> [Rose a]

      

basically equivalent to

data Rose a = Node a [Rose a]

      

In other words, it Node

is a data structure containing a database and a list of child nodes. But in the above definition, instead of naming it Node

, it was called :>

. It's just a fictitious name; Haskell allows you to create custom operators like this.

If a name is used Node

, you can write

root (Node datum children) = datum

      



Or, more briefly,

root (Node a rs) = a

      

Since the name is actually given :>

, you need to write it as

root (a :> rs) = a

      

In particular, you are trying to use Rose

, but it is a type constructor, not a value constructor. Similarly, you are trying to use the " :

" operator , but for lists, not rose trees.

Hope this clears things up for you.

+9


source







All Articles