[英]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
. 我想使用错误函数
getNodeValue
来加入我树的根节点的'Label'(节点值)。 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. 我想你想在这里使用模式匹配来“查看”Tree数据类型。 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]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.