20-CS-4003-001 Organization of Programming Languages Fall 2017
Monads

Lambda calculus, Type theory, Formal semantics, Program analysis

Prev     Next     All lectures

Monadic Operators


  -  
  • filterM :: Monad m => (a -> m Bool) -> [a] -> m [a]
    Filters out all elements list [a] for which (a -> m Bool) evaluates to False. The result is a list inside a monad of the same type.
    For example: filterM (\x -> Just (x > 0)) [2, 1, 0, -1]
    evaluates to Just [2,1].

  • foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
    Monadic version of foldl. The first argument takes a function of 2 underlying types that returns a monadic value and where the first argument is an accumulator. The second argument initializes the accumulator. The third argument is a list of underlying typed objects that is to be folded. The folded value is a monad.
    For example: foldM (\acc x -> Just (x + acc)) 0 [1,2,3,4]
    evaluates to Just 10.

  • liftM :: Monad m => (a1 -> r) -> m a1 -> m r
    Lets a non-monadic function (1st argument) operate on the contents of a monad (2nd argument).
    For example: liftM head (Just [23,24,25])
    evaluates to Just 23 this is not possible if liftM is removed from the above.

  • mapM :: Monad m => (a -> m b) -> [a] -> m [b]
    Applies a monadic function (1st argument) to each element of a non-monadic list (2nd argument) resulting in a list inside a monad.
    For example: mapM (\x -> (Just x)) [1,2,3,4]
    evaluates to Just [1,2,3,4].

  • sequence :: Monad m => [m a] -> m [a]
    Evaluates all monadic values in the input list from left to right and returns a list of the "contents" of these monads, placing this list in a monad of the same type. Evaluation can be interpreted as "performing an action", for example in the case of print.
    For example: sequence [print 1, print 2, print 3] evaluates to 1 2 3 [(),(),()].
    sequence [(Just 3), (Just 4), (Just 5)]
    evaluates to Just [3,4,5]

  • unless :: Monad m => Bool -> m () -> m ()
    Executes a monadic expression (2nd argument) when the first argument evaluates to False.
    For example: unless (False) (print "OK")

  • when :: Monad m => Bool -> m () -> m ()
    Executes a monadic expression (2nd argument) when the first argument evaluates to True.
    For example: when (1 == 1) (print "OK")

  • guard :: MonadPlus m => Bool -> m ()
    Returns () if its argument is True, otherwise it returns mzero.
    For example: guard True >>= (\x -> (Just x))
    evaluates to Just ()
    guard False >>= (\x -> (Just x))
    evaluates to Nothing

  • mzero :: MonadPlus m => m a
    The zero of the MonadPlus class.
    For example: mzero::[Int] is [],
    mzero::Maybe Char is Nothing

  • mplus :: MonadPlus m => m a -> m a -> m a
    The plus of the MonadPlus class.
    For example: mplus "hello" "there" is "hellothere"