Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-Then-Else inside List Monads do-notation

Tags:

haskell

monads

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 
like image 524
AlphaEpsilon Avatar asked Jun 09 '20 01:06

AlphaEpsilon


1 Answers

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:

  • How are list comprehensions implemented in Haskell?
  • Why is guard based on Alternative?
  • The List monad - Learn You a Haskell for Great Good!
  • List comprehension translations - Haskell Report 2010
like image 162
snipsnipsnip Avatar answered Oct 13 '22 04:10

snipsnipsnip