我一直在研究Haskell 幺半群及其用途,这让我对幺半群的基础有了相当好的理解。博客文章中介绍的其中一件事是 Any monoid,它的用法如下:
foldMap (Any . (== 1)) tree
foldMap (All . (> 1)) [1,2,3]
同样,我一直在尝试构建一个最大幺半群,并提出了以下内容:
newtype Maximum a = Maximum { getMaximum :: Maybe a }
deriving (Eq, Ord, Read, Show)
instance Ord a => Monoid (Maximum a) where
mempty = Maximum Nothing
m@(Maximum (Just x)) `mappend` Maximum Nothing = m
Maximum Nothing `mappend` y = y
m@(Maximum (Just x)) `mappend` n@(Maximum (Just y))
| x > y = m
| otherwise = n
我可以为特定类型构造一个最大幺半群——例如,很容易说 Num,但希望它对任何东西都有用(显然要求任何东西都是 Ord 的实例)。
此时我的代码可以编译,但仅此而已。如果我尝试运行它,我会得到:
> foldMap (Just) [1,2,3]
<interactive>:1:20:
Ambiguous type variable `a' in the constraints:
`Num a' arising from the literal `3' at <interactive>:1:20
`Monoid a' arising from a use of `foldMap' at <interactive>:1:0-21
Probable fix: add a type signature that fixes these type variable(s)
我不确定这是因为我说错了,还是因为我的幺半群不正确,或者两者兼而有之。我很感激任何关于我哪里出错的指导(在逻辑错误和非惯用的 Haskell 用法方面,因为我对这种语言非常陌生)。
- 编辑 -
Paul Johnson 在下面的评论中建议将 Maybe 排除在外。我的第一次尝试如下所示:
newtype Minimum a = Minimum { getMinimum :: a }
deriving (Eq, Ord, Read, Show)
instance Ord a => Monoid (Minimum a) where
mempty = ??
m@(Minimum x) `mappend` n@(Minimum y)
| x < y = m
| otherwise = n
但我不清楚如何表达 mempty 而不知道 a 的 mempty 值应该是什么。我怎么能概括这个?