[英]Haskell accessing fields in custom data types
對於賦值,我必須為自定義數據類型樹實現不同的函數(如下定義)
我想使用錯誤函數getNodeValue
來加入我樹的根節點的'Label'(節點值)。 我非常感謝有關如何做到這一點的一些幫助!
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? ...}
我想你想在這里使用模式匹配來“查看”Tree數據類型。 要獲取提供的樹的根節點的值,您必須執行以下操作:
getNodeValue :: Tree -> Label
getNodeValue (Node _ l _) = l
如果允許更改類型定義,則還可以使用記錄語法自動生成訪問器:
data Tree = Node
{ getUpdater :: (Label -> Label)
, getNodeValue :: Label
, getSubnodes :: [Tree]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.