好吧Maybe
,MonadPlus
例如
instance MonadPlus Maybe where
mempty = Nothing
并guard
实现为
guard b = if b then return () else mempty
-- = if b then Just () else Nothing
有了这些知识,您可以使用等式推理来推断,当m
is时Maybe
,您可以替换原始代码
monadPlusSDif x y = guard (y /= 0) >> return (div x y)
和
monadPlusSDif x y = (if y /= 0
then Just ()
else Nothing) >> Just (div x y)
或者
monadPlusSDif x y
| y /= 0 = Just () >>= \_ -> Just (div x y)
| otherwise = Nothing >>= \_ -> Just (div x y)
或者
monadPlusSDif x y
| y /= 0 = Just (div x y)
| otherwise = Nothing
或者
monadPlusSDif x y
| y == 0 = Nothing
| otherwise = Just (div x y)
所以你看到功能是相同的。