What would the Foldable instance for this datatype look like?
这个数据类型的Foldable实例是什么样的?
data X t = X t [X t]
I tried this:
我试过这个:
instance Foldable X where
foldMap f (X x xs) = f x `mappend` foldMap f xs
But got this error:
但得到了这个错误:
Occurs check: cannot construct the infinite type: a = X a
When generalising the type(s) for `foldMap'
In the instance declaration for `Foldable X'
1 个解决方案
#1
xs
is a list of items and foldMap
needs to be applied to the individual items, not the list itself. Doing this with map
gives a list of results that can be combined with mconcat
:
xs是项目列表,foldMap需要应用于单个项目,而不是列表本身。使用map执行此操作会给出可以与mconcat结合使用的结果列表:
instance Foldable X where
foldMap f (X x xs) = f x `mappend` mconcat (map (foldMap f) xs)
#1
xs
is a list of items and foldMap
needs to be applied to the individual items, not the list itself. Doing this with map
gives a list of results that can be combined with mconcat
:
xs是项目列表,foldMap需要应用于单个项目,而不是列表本身。使用map执行此操作会给出可以与mconcat结合使用的结果列表:
instance Foldable X where
foldMap f (X x xs) = f x `mappend` mconcat (map (foldMap f) xs)