haskell - 在 Haskell 中使用 Maybe 写一个最大 Monoid

标签 haskell monoids

我一直在经历Haskell monoids and their uses ,这让我对幺半群的基础有了相当好的理解。博客文章中介绍的其中一件事是 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 值应该是什么。我怎么能概括这个?

最佳答案

传递给 foldMap 的函数需要返回一个幺半群,在本例中为 Maximum a :

> foldMap (Maximum . Just) [1,2,3]
Maximum {getMaximum = Just 3}

关于haskell - 在 Haskell 中使用 Maybe 写一个最大 Monoid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5344164/

相关文章:

haskell - 关于 Haskell 中的 ~ 和 @ 运算符的问题

Haskell:以良好的方式命名多个参数

haskell - 在 Eq 实例实现中仅覆盖少数情况的数据

haskell - Free Monoid 和 Monoid 之间的主要区别是什么?

scala - 到底什么是幺半群同态?

Haskell——理解编写器类型声明

haskell - 使用 fromList 创建 SEXP 向量

haskell - FoldMap 采用错误类型的参数?

haskell - 笛卡尔类的这些类扩展是做什么用的?

haskell - 复合模式是否可以用于从树生成 HTML 并处理缩进,或者这本质上是不可能的?