对于所有表现良好的 Monad,以下两种 flatten 实现是否等效?
flatten1 xss = do
xs <- xss
x <- xs
return x
flatten2 xss = do
xs <- xss
xs
对于所有表现良好的 Monad,以下两种 flatten 实现是否等效?
flatten1 xss = do
xs <- xss
x <- xs
return x
flatten2 xss = do
xs <- xss
xs
是的,它们是相同的。它们被脱糖为
flatten1 xss =
xss >>= \xs -> xs >>= \x -> return x
flatten2 xss = do
xss >>= \xs -> xs
第一个相当于
xss >>= \xs -> xs >>= return
并且由右身份单子定律等价于
xss >>= \xs -> xs
简而言之,是的。为了证明它:
你写过:
xss >>= (\xs -> xs >>= \x -> return x)
xss >>= (\xs -> xs >>= return) -- eta
在第一个和
xss >>= (\xs -> xs)
xss >>= id
根据单子定律,return
是一个正确的身份,因此
m >>= return === m
所以我们可以做
xss >>= (\ xs -> xs >>= return )
xss >>= (\ xs -> xs )
xss >>= id