簡體   English   中英

數據樹的Haskell可折疊實例

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM