[英]Haskell foldable instance for data tree
嘗試使用以下代碼為數據樹創建可折疊實例:
data Rose a = a :> [Rose a]
deriving (Eq, Show)
instance Foldable Rose where
fold (a:>b) = a <> (map fold b)
但是這段代碼不起作用,它產生的錯誤:
Could not deduce <m ~ [m]>
from the context <Monoid m>
bount by the type signature for fold :: Monoid m => Rose m -> m
...
In the return type of a call of 'map'
...
有誰知道為什么/如何使它工作?
當您編寫fold b
,您正在將Foldable
實例用於列表。 因此, fold
將幺半群值列表折疊為單個值。 這個monoidal值的類型恰好是Rose a
(這是你的列表所包含的)。 但那可能不是你想要的。
嘗試使用foldMap fold
而不是fold
。 這樣,您首先折疊列表中的每個Rose a
,然后將結果折疊在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.