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

Monads |

Prev
Next
All lectures
Code

**Examples**

import Control.Monad f = (\ x -> if (x == 0) then fail "zero" else Just (x+1)) v1 = Just 5 >>= f v2 = Just 0 >>= f v3 = Nothing >>= f v4 = f 0 v5 = f 5 v1' = f =<< Just 5 v2' = f =<< Just 0 v3' = f =<< Nothing v6 = ap [(+1),(+2),(+3)] [1,2,3] v7 = fail "test" :: Maybe Int v8 = fail "test" :: Maybe [Int] v9 = fail "test" :: IO () v10 = filterM (\x -> Just (x > 0)) [2, 1, 0, -1] (./.) :: Fractional a => a -> a -> Maybe a x ./. 0 = Nothing x ./. y = Just (x / y) divide :: Fractional a => a -> [a] -> Maybe a divide x ys = foldM (./.) x ys v11 = divide 128 [2,4,8] v12 = divide 8 [2,3,4,0,6,7] v13 = guard True >> Just 3 v14 = guard False >> Just 3 v15 = liftM head (Just [23,24,25]) v16 = liftM tail (Just [23,24,25]) v17 = mzero :: [Int] v18 = mzero :: Maybe Int v19 = mplus "a" "b" v20 = mplus (Just "a") (Just "b") v21 = mplus (Just 10) (Just 20) v22 = mplus mzero (Just 10) v23 = mplus (Just 10) mzero v24 = (return 3) :: Maybe Int v25 = (return 3) :: [Int] v26 = getLine >>= (\x -> return (x ++ " " ++ x)) >>= print v27 = sequence [print 1, print 2, print 3] >>= print v28 = sequence [Just 1, Just 2, Just 3] v29 = unless (0 == 1) (print "OK") v30 = when (1 == 1) (print "OK") |
- |
The operator filerM filters out all elements of 2nd argument
that do not satisfy the 1st argument which is a function that returns
a value of type Monad m => m Boolv10
has value Just [2,1].
The operator
The operator
The operator
The operator
The operator
The operator
The operator v28 displays
Just [1,2,3].
The operator
The operator Monads are useful in any situation where the programmer wants to carry out a purely functional computation while a related computation is carried out on the side. In imperative programming the side effects are embedded in the semantics of the programming language; with monads, they are made explicit in the monad definition, thus avoiding errors by action at a distance. |