简体   繁体   中英

Haskell accessing fields in custom data types

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? ...}

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

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]
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM