CSCE 314 Lecture 20

From Notes
Jump to navigation Jump to search

« previous | Wednesday, October 12, 2011 | next »


Quiz

-- No. 1
class Monad m where
    (>>=) :: m a -> (a -> m b) -> m b
    return :: a -> m a
    (>>) :: m a -> m b -> m b

-- No. 2
data Maybe a = Nothing | Just a
instance Monad Maybe where
    return = Just
    m >>= f = case m of
        Nothing -> Nothing
        Just x -> f x

More Random Stuff

Use randomIO from System.Random to read a random number from within a do construct.

test2 = do    
    let randActions = (replicate 5 randomIO) :: [IO Int] 
    rands <- sequence randActions
           
    print rands           
    putStrLn ""
   
    let randActions2 = filterM (\_ -> do
                                   r <- randomIO :: IO Int
                                   return $ even r) [1..10] 
    randActions2 >>= print
    randActions2 >>= print
    randActions2 >>= print
    randActions2 >>= print
                  
    putStrLn ""

This code randomly selects numbers from a list from 1 to 10

Control Structures and Basic Operations

forever :: IO a -> IO b    -- why this type? this function never returns, so it "diverges"
forever a = a >> forever a

forM_ :: [a] -> (a -> IO b) -> IO ()
forM [] fa = return ()
forM (n:ns) fa = fa n >> forM_ ns fa

-- alternate definition
forM_ ns fa = sequence_ (map fa ns)

sequence_ :: [IO a] -> IO ()
sequence_ xs = foldr (>>) (return ()) xs

sequence :: [IO a] -> IO [a]
sequence_ :: [IO a] -> IO ()

mapM :: (a -> IO b) -> [a] -> IO [b]
mapM_ :: (a -> IO b) -> [a] -> IO ()

forM :: [a] -> (a -> IO b) -> IO [b]
forM_ :: [a] -> (a -> IO b) -> IO ()

filterM :: (a -> IO Bool) -> [a] -> IO [a]

foldM :: (a -> b -> IO a) -> a -> [b] -> IO a
foldM_ :: (a -> b -> IO a) -> a -> [b] -> IO ()

when :: Bool -> IO () -> IO ()

Interesting note: list monads do some weird things...