我一直在学习宾夕法尼亚大学的CS194,目前正在学习第七课单子(Monads)。我以为我对单子有了一个不错的理解,直到我看到序列(sequence)函数的实现并开始探究。
sequence :: Monad m => [m a] -> m [a]
sequence [] = return []
sequence (ma:mas) = do
a <- ma
as <- sequence mas
return (a:as)
乍一看似乎很直观,但是当我深入探究时,遇到了一堆问题:
The type of
return []
is :return [] :: Monad m => m [t]
. Earlier in the same lesson, theMonad
instance for[]
defines return as:return x = [x]
. How did this lead to the type signaturem [t]
forreturn []
?a <- ma
. What is type ofa
here, assuming I called sequence with[Just 5, Just 9]
? By theMonad
instance definition ofMaybe
:Just x >>= k = k x
I would think
x
, ora
in the case ofsequence
would be aNum
. But it must really be aMonad
ofNum
. How didx
become a monad ofNum
here whenJust x
from the instance definition ofMaybe
seems to be pullingx
out ofJust
?
return []
不是像[]
的 monad 实例中的\x -> [x]
函数 - 它是来自m
monad 的return
函数(因此结果将取决于m
的实际情况)- 如果有帮助,请考虑m = Maybe
- 因此return []
将是Just []
。 - Random Devsequence [Just 5, Just 9]
,那么a
的类型将是一些Num
(a
将是5
和9
) - 在Num
/5
中没有 "Monad" - 你可以说它在Just
中 ;) - Random Dev