2009-04-19 63 views
1

這個數據類型的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' 

回答

6

xs將被應用到各個項目的項目和foldMap需求的列表,不在名單本身。與map一起做出的結果列表可以與mconcat結合:

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