Haskell accessing fields in custom data types

1.6k Views Asked by At

For an assignment I have to implement different functions for the custom data type tree (as defined below)

I would like to accees the 'Label' (node-value) of the root node of my tree using the faulty function getNodeValue. I'd be very grateful for some help on how to do this!

data Tree = Node (Label -> Label) Label [Tree]
type Label = Int

testTree = Node (+1) 0 [Node (+1) 1 [], Node (+1) 2 [], Node (+1) 3 []]

getNodeValue :: Tree -> Label
getNodeValue t = {... how does I custom types? ...}
2

There are 2 best solutions below

2
On BEST ANSWER

I think you want to use a pattern match here to 'look' inside the Tree datatype. To get the value of the root node of the supplied tree you would have to do something like this:

getNodeValue :: Tree -> Label
getNodeValue (Node _ l _) = l
0
On

If changing the type definition is allowed, it is also possible to use the record syntax to have accessors automatically generated:

data Tree = Node
    { getUpdater :: (Label -> Label)
    , getNodeValue :: Label
    , getSubnodes :: [Tree]
    }