Maybe
表示在计算过程中由于错误可能不会产生结果。因此,这种计算必须被短路。
现在 Maybe
的 Semigroup/Monoid 实例似乎违反了这个语义,因为前者偏向于 Just
,而后者将错误情况 Nothing
视为其空元素:
Just "foo" <> Nothing -- Just "foo"
Nothing <> Just "bar" -- Just "bar"
Just "foo" <> Just "bar" -- Just "foobar"
Nothing <> Nothing -- Nothing
在前两种情况下,我希望你能返回Nothing
。
这是另一种实现方式(希望它是正确/合法的):
instance Semigroup a => Semigroup (Maybe a) where
Nothing <> _ = Nothing
_ <> Nothing = Nothing
Just a <> Just b = Just (a <> b)
instance Monoid a => Monoid (Maybe a) where
mempty = Just mempty
我不想说这些替代方案更好。但它们也很有用。那么,为什么一开始就要做出选择,而不是让用户自己实现呢?
0
,且0 + x = x + 0 = x
。 - Willem Van Onsema
有一个mempty
,对吗? - Willem Van Onsem