将`do notation`转换为>> = v.map

Kev*_*ith 3 haskell

给出以下do notation代码:

do
 a <- return 1
 b <- [10,20]
 return $ a+b
Run Code Online (Sandbox Code Playgroud)

是否有更惯用的转换:

ghci> return 1 >>= (\x -> map (+x) [10, 20])
[11,21]
Run Code Online (Sandbox Code Playgroud)

ghci> return 1 >>= (\x -> [10, 20] >>= (\y -> [y+x]))
[11,21]
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 13

do 符号映射到monadic函数,所以严格地说你写

 return 1 >>= (\a -> [10, 20] >>= (\b -> return $ a+b ))
Run Code Online (Sandbox Code Playgroud)

现在,你可以替换>>= … return由刚fmap

 return 1 >>= (\x -> fmap (\y -> x+y) [10, 20])
Run Code Online (Sandbox Code Playgroud)

并使用部分,并将常量1直接废弃到函数中

 fmap (1+) [10, 20]
Run Code Online (Sandbox Code Playgroud)

或者,如果您真的想从列表中获取第一个加号,我建议使用liftM2:

 liftM2 (+) [1] [10, 20]
Run Code Online (Sandbox Code Playgroud)

比这更惯用,并且具有相同的结果,是Applicative列表的实例:

(+) <$> [1] <*> [10, 20]
Run Code Online (Sandbox Code Playgroud)