[英]Are Maybe String and Maybe Int both Monoids in Haskell?
我对 Maybe Int 和 Maybe String 是否都是 Haskell 中的幺半群感到有些困惑,因为我真的不知道你可以将哪些函数应用到具有中性元素和关联性规则的幺半群方面? 有人可以帮帮我吗?
Maybe
类型的Monoid
实例已定义为[src] :
instance Semigroup a => Monoid (Maybe a) where mempty = Nothing
因此,它要求Int
或String
是Semigroup
类型 class的实例。 由于String
与type String = [Char]
相同,因此是Char
的列表,因此确实如此, 我们确实看到了[src] :
instance Semigroup [a] where (<>) = (++) {-# INLINE (<>) #-} stimes = stimesList
所以它将 append 两个列表,对于Maybe
这意味着[src] :
instance Semigroup a => Semigroup (Maybe a) where Nothing <> b = ba <> Nothing = a Just a <> Just b = Just (a <> b) stimes = stimesMaybe
因此,这意味着对于两个Maybe String
s,中性元素是Nothing
并且二元运算符将 append 包裹在Just …
数据构造函数中的两个字符串,如果它们都是Just
s,如果两者之一是Just
,则Just
一个,或者如果两个项目都是Nothing
,则Nothing
。
确实, Int
并非如此。 对于整数,可以有多个Monoid
实例,例如 ⟨ℤ,+, 0⟩ 或 ⟨ℤ,×, 1⟩。
只要a
本身有一个Monoid
实例,任何Maybe a
都有一个Monoid
实例; 两个Just
值的组合只是根据它们的实例组合包装的值,而任何与Nothing
组合的东西本身就是Nothing
。
String
有一个Monoid
实例,因为它是[Char]
的别名; 所有列表都是通过列表连接以空列表作为标识的幺半群。 因此, Maybe String
也是一个幺半群。
> Just "Fo" <> Just "o"
Just "Foo"
> Just "Fo" <> Nothing
Nothing
Maybe Int
不是幺半群,因为Int
不是幺半群。 这是因为如何使Int
成为幺半群有多种选择,因此没有一个选择被选为特殊的。 相反,使用不同的Monoid
实例定义了几种新类型,以阐明您要使用的操作。
> import Data.Monoid
> (3 :: Int) <> 5
<interactive>:8:1: error:
• No instance for (Semigroup Int) arising from a use of ‘<>’
• In the expression: (3 :: Int) <> 5
In an equation for ‘it’: it = (3 :: Int) <> 5
-- (+) and 0
> Sum (3 :: Int) <> Sum 5
Sum {getSum = 8}
-- (*) and 1
> Product (3 :: Int) <> Product 5
Product {getProduct = 15}
> Just (Sum (3 :: Int)) <> Just (Sum 5)
Just (Sum {getSum = 8})
> Just (Sum (3 :: Int)) <> Nothing
Nothing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.