无法理解“MonadPlus”类型类的不同实例的源代码
Trouble understanding the source code of different instances of `MonadPlus` typeclass
我正在查看 MonadPlus
类型类及其实例 Maybe
、[]
等的源代码。我没有找到这些实例的方法 - mzero
或 mplus
定义。这是 MonadPlus
的 Maybe
实例的 source code:
class (Alternative m, Monad m) => MonadPlus m where
mzero :: m a
mzero = empty
mplus :: m a -> m a -> m a
mplus = (<|>)
instance MonadPlus Maybe
虽然在 Chapter 15 of Real World Haskell 中它说以下是 mzero
和 mplus
的标准定义 Maybe
和 []
.
class Monad m => MonadPlus m where
mzero :: m a
mplus :: m a -> m a -> m a
instance MonadPlus [] where
mzero = []
mplus = (++)
instance MonadPlus Maybe where
mzero = Nothing
Nothing `mplus` ys = ys
xs `mplus` _ = xs
所以基本上我的问题是为什么会有差异?
mzero = empty
和 mplus = (<|>)
行指定默认实现,任何实现者都可以覆盖。 empty
和 (<|>)
来自 Alternative
typeclass,它是为 Maybes 定义的,并且这样列出:
instance Alternative Maybe where
empty = Nothing
Nothing <|> r = r
l <|> _ = l
instance Alternative [] where
empty = []
(<|>) = (++)
因此,Alternative
定义已经与默认的 MonadPlus
定义匹配,因此他们可以简单地编写 instance MonadPlus Maybe
并使用默认值。
从本质上讲,标准定义仍然是正确的,它只是扩展了默认值并将 Alternative
排除在外。
我正在查看 MonadPlus
类型类及其实例 Maybe
、[]
等的源代码。我没有找到这些实例的方法 - mzero
或 mplus
定义。这是 MonadPlus
的 Maybe
实例的 source code:
class (Alternative m, Monad m) => MonadPlus m where
mzero :: m a
mzero = empty
mplus :: m a -> m a -> m a
mplus = (<|>)
instance MonadPlus Maybe
虽然在 Chapter 15 of Real World Haskell 中它说以下是 mzero
和 mplus
的标准定义 Maybe
和 []
.
class Monad m => MonadPlus m where
mzero :: m a
mplus :: m a -> m a -> m a
instance MonadPlus [] where
mzero = []
mplus = (++)
instance MonadPlus Maybe where
mzero = Nothing
Nothing `mplus` ys = ys
xs `mplus` _ = xs
所以基本上我的问题是为什么会有差异?
mzero = empty
和 mplus = (<|>)
行指定默认实现,任何实现者都可以覆盖。 empty
和 (<|>)
来自 Alternative
typeclass,它是为 Maybes 定义的,并且这样列出:
instance Alternative Maybe where
empty = Nothing
Nothing <|> r = r
l <|> _ = l
instance Alternative [] where
empty = []
(<|>) = (++)
因此,Alternative
定义已经与默认的 MonadPlus
定义匹配,因此他们可以简单地编写 instance MonadPlus Maybe
并使用默认值。
从本质上讲,标准定义仍然是正确的,它只是扩展了默认值并将 Alternative
排除在外。