Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting `do notation` to >>= v. map

Tags:

haskell

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]
like image 631
Kevin Meredith Avatar asked Jun 24 '26 16:06

Kevin Meredith


1 Answers

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]
like image 142
Bergi Avatar answered Jun 28 '26 16:06

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!