我有以下数据类型:
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 ofBool
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
如果我们选择 Fools
如 mempty = 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/