haskell - 类型的标识是什么?

标签 haskell math monoids

我有以下数据类型:

data Bull = Fools
  | Twoo
  deriving (Eq, Show)

并使用 Monoid 来实现它:
instance Monoid Bull where
  mempty = Fools
  mappend _ _ = Fools

如您所见,mempty是恒等律不成立的恒等函数:
*Main> x = Twoo
*Main> mappend mempty x == x
Bull的身份是什么?类型?Bool的身份是什么?类型?

最佳答案

简答 : 它取决于 mappend功能 .

What would be the identity of Bull type? What is the identity of Bool type?


A型有没有“固有”身份 ,单位元素只存在于二元函数(这里是 mappend ),如 Wikipedia article says :

In mathematics, an identity element or neutral element is a special type of element of a set with respect to a binary operation on that set, which leaves other elements unchanged when combined with them.


所以这取决于什么操作mappend是。
如果是 Bool如果我们定义 mappend = (&&) ,那么单位元素是 mempty = True .但是如果我们选择 mappend = (||) ,然后 mempty = False .
您的 instance Moniod Bull不正确 .由于它不能满足性质:
mappend mempty x = x
如果我们选择 Foolsmempty = Fools ,然后 mappend Fools Twoo应该是 Twoo .如果我们选择 mempty = Twoo ,然后 mappend Twoo Twoo仍然不是Twoo .
一个Monoid的点是你必须仔细设计二元运算符。喜欢 Haskell documentation on Monoid 说,它应该满足以下规则:
mappend mempty x = x

mappend x mempty = x

mappend x (mappend y z) = mappend (mappend x y) z

mconcat = foldr mappend mempty

这些规则不是为 Haskell“发明”的:幺半群是众所周知的 algebraic structure .通常在数学中,幺半群表示为三元组。例如 (N, +, 0) ,其中 N 是这里的集合(例如自然数),+ 是二元函数,0 是单位元素。

关于haskell - 类型的标识是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44761991/

相关文章:

haskell - 为什么将未定义函数与未装箱类型一起使用时是多态的?

javascript - 3 维空间中的轨道倾 Angular

python - 列表列表 vs 字典

haskell - 在 Haskell 中寻找自由幂等幺半群的元素的最小形式

scala - Monoid 类型注释

haskell - Yesod,如何从 Javascript/Julius 中的 JSON 数据生成类型安全链接

list - OCaml 有像 Haskell 的++ 那样的语法吗?

parsing - 幺半群分析——它是什么?

haskell - Haskell 有更好的方法吗?

c++ - 我怎样才能从 n 得到一个自次幂等于 n 的数?