[英]Define bind without join for the list monad in Haskell
I understand the definition of >>=
in term of join
我了解>>=
在join
的定义
xs >>= f = join (fmap f xs)
which also tells us that fmap + join
yields >>=
这也告诉我们fmap + join
产生>>=
I was wondering if for the List
monad it's possible to define without join
, as we do for example for Maybe
: 我想知道List
Monad是否可以不使用join
进行定义,例如对Maybe
:
>>= m f = case m of
Nothing -> Nothing
Just x -> f x
Sure. 当然。 The actual definition in GHC/Base.hs
is in terms of the equivalent list comprehension: GHC/Base.hs
的实际定义是根据等效列表理解的:
instance Monad [] where
xs >>= f = [y | x <- xs, y <- f x]
Alternatively, you could try the following method of working it out from scratch from the type: 或者,您可以尝试使用以下方法从该类型从头开始进行计算:
(>>=) :: [a] -> (a -> [b]) -> [b]
We need to handle two cases: 我们需要处理两种情况:
[] >>= f = ???
(x:xs) >>= f = ???
The first is easy. 首先很容易。 We have no elements of type a
, so we can't apply f
. 我们没有类型a
元素,因此不能应用f
。 The only thing we can do is return an empty list: 我们唯一能做的就是返回一个空列表:
[] >>= f = []
For the second, x
is a value of type a
, so we can apply f
giving us a value of fx
of type [b]
. 对于第二个, x
是类型a
的值,因此我们可以应用f
给我们提供类型[b]
的fx
值。 That's the beginning of our list, and we can concatenate it with the rest of the list generated by a recursive call: 这是我们列表的开始,我们可以将其与递归调用生成的列表的其余部分连接起来:
(x:xs) >>= f = f x ++ (xs >>= f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.