Reputation: 41939
Given the following do notation
code:
do
a <- return 1
b <- [10,20]
return $ a+b
Is there a more idiomatic conversion:
ghci> return 1 >>= (\x -> map (+x) [10, 20])
[11,21]
versus
ghci> return 1 >>= (\x -> [10, 20] >>= (\y -> [y+x]))
[11,21]
Upvotes: 3
Views: 93
Reputation: 665195
do
notation maps to monadic functions, so strictly you'd write
return 1 >>= (\a -> [10, 20] >>= (\b -> return $ a+b ))
Now, you can replace that >>= … return
by just fmap
return 1 >>= (\x -> fmap (\y -> x+y) [10, 20])
and use sections, and scrap that constant 1
right into the function
fmap (1+) [10, 20]
Alternatively, if you really want to take your first summand from a list, I'd recommend to use liftM2
:
liftM2 (+) [1] [10, 20]
A bit more idiomatic than this, and with the same results, is the Applicative
instance of lists:
(+) <$> [1] <*> [10, 20]
Upvotes: 13