I am trying to understand the concept of Monads and came across this list comprehension syntax for filtering sums from 2 lists.
largeSums = [i+j | i <- [10, 20, 30], j <- [1 , 2] , (i+j)>20]
I am trying to rewrite this using the do notation but do not understand what goes inside the else
part:
largeSums = do
i <- [10, 20, 30]
j <- [1 , 2]
if i+j > 20
then return (i+j)
else
An empty list without return
will work in that case. (which means 'no result for this combination of (i, j)'. On the other hand, return (i+j)
equals [i+j]
)
largeSums = do
i <- [10, 20, 30]
j <- [1 , 2]
if i+j > 20
then return (i+j)
else []
However, it is more idiomatic to use guard :: (Alternative f) => Bool -> f ()
.
import Control.Monad
largeSums = do
i <- [10, 20, 30]
j <- [1 , 2]
guard (i+j > 20)
return (i+j)
Related links:
guard
based on Alternative
?If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With