作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有人可以解释类型的含义以及如何实现吗?
class Foldable f where
foldMap :: (Monoid m) => (a -> m) -> f a -> m
foldMap f = mconcat . (<$>) f
但我收到了这个错误:
• Couldn't match type ‘f’ with ‘[]’
‘f’ is a rigid type variable bound by
the class declaration for ‘Foldable’
at traversable.hs:41:16
Expected type: f a -> m
Actual type: [a] -> m
• In the expression: mconcat . (<$>) f
In an equation for ‘foldMap’: foldMap f = mconcat . (<$>) f
• Relevant bindings include
foldMap :: (a -> m) -> f a -> m (bound at traversable.hs:45:3)
error:
• Could not deduce (Data.Foldable.Foldable f)
arising from a use of ‘foldr’
from the context: Foldable f
bound by the class declaration for ‘Foldable’
at traversable.hs:41:7-14
or from: Monoid m
bound by the type signature for:
foldMap :: forall m a. Monoid m => (a -> m) -> f a -> m
at traversable.hs:42:14-47
Possible fix:
add (Data.Foldable.Foldable f) to the context of
the type signature for:
foldMap :: forall m a. Monoid m => (a -> m) -> f a -> m
or the class declaration for ‘Foldable’
• In the expression: foldr (\ x -> mappend (f x)) mempty
In an equation for ‘foldMap’:
foldMap f = foldr (\ x -> mappend (f x)) mempty
最佳答案
they explained it as "Map each element of the structure to a monoid, and combine the results." but I don't quite understand what it means. How can I map an element to the structure of a Monoid?
a -> m
来做到这一点.所以我们自己定义了“映射”函数。
Foldable
class 成员的类型是可以“折叠”的数据结构。这意味着,例如,如果您有一个
Tree
包含
Int
s,所以
Tree Int
,这样你,对于一个函数
f :: Int -> Int -> Int
,和一个中性元素
z
,你可以得到一个
Int
.
foldMap
我们将调用一个函数
f :: a -> m
在这些元素上,并使用幺半群函数 ⊕ 来“折叠”这些值。对于实现
Functor
的数据结构因此,它或多或少相当于
foldMap f = foldr mappend mempty . fmap f
.
f
在
foldr
函数本身,例如:
foldMap' :: (Foldable f, Monoid m) => (a -> m) -> f a -> m
foldMap' f x = foldr (\y -> mappend (f y)) mempty x
foldMap' :: (Foldable f, Monoid m) => (a -> m) -> f a -> m
foldMap' f = foldr (mappend . f) mempty
f
预处理数据结构中的值。将它们转换为幺半群对象,我们调用
mappend
作为这些项目的折叠功能。
关于haskell - foldMap::(Monoid m) => (a -> m) -> f a -> m 类型是什么意思以及如何实现它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58164820/
我是一名优秀的程序员,十分优秀!