6

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 

1 Answer 1

5

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:

Sign up to request clarification or add additional context in comments.

1 Comment

pure > return

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.