gpt4 book ai didi

haskell - 类型的标识是什么?

转载 作者:行者123 更新时间:2023-12-01 06:56:59 29 4
gpt4 key购买 nike

我有以下数据类型:

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com