簡體   English   中英

定義看似簡單的Foldable實例

[英]Defining a seemingly simple Foldable instance

此數據類型的Foldable實例是什么樣的?

data X t = X t [X t]

我嘗試了這個:

instance Foldable X where
    foldMap f (X x xs) = f x `mappend` foldMap f xs

但是得到了這個錯誤:

Occurs check: cannot construct the infinite type: a = X a
When generalising the type(s) for `foldMap'
In the instance declaration for `Foldable X'

xs是項目列表,並且foldMap需要應用於單個項目,而不是列表本身。 使用map給出可以與mconcat結合使用的結果列表:

instance Foldable X where
  foldMap f (X x xs) = f x `mappend` mconcat (map (foldMap f) xs)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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