-- runhaskell QA.hs module QA where -- 1. Monads -- 2. Typeclass Instances -- 3. Monoids -- 4. WHNF -- 5. Laws import Prelude hiding (log, Semigroup(..), Monoid(..), foldMap, concatMap) import Control.Monad.State import Data.Sequence (Seq) import qualified Data.Sequence -------------------------------------------------------------------------------- -- 0) Some setup data Severity = Warn | Critical deriving (Show,Eq) data Log = Log Severity -- Last severity used [String] -- the warnings [String] -- criticals deriving (Show) addMsg :: String -> Log -> Log addMsg msg (Log lvl warns crits) = case lvl of Warn -> Log lvl (warns ++ [msg]) crits Critical -> Log lvl warns (crits ++ [msg]) numMsgs :: Log -> Int numMsgs (Log _ warns crits) = length warns + length crits -------------------------------------------------------------------------------- -- 1. Monads -- State s a -- = a computation that returns an 'a' while using some (internal) state of type 's' foo :: State s a foo = undefined -- a computation that returns an 'a' while using some (internal) state of type 's' bar :: i -> a bar = undefined -- a (pure) computation that takes an 'i' as input and produces an 'a' as output -- get :: State s s -- put :: s -> State s () -- | Log the message at the current log level and return the total number of -- messages in the log log :: String -> State Log Int log msg = do theLog <- get let theLog' = addMsg msg theLog put theLog' return (numMsgs theLog') -- a) Convert log to use >>=, return, and >> log msg = get >>= \theLog -> let theLog' = addMsg msg theLog in put theLog' >> return (numMsgs theLog') -- | A Stateful computation to compute fibonacci numbers that logs -- whenever we make a recursive call. fib :: Int -> State Log Int fib 0 = return 0 fib 1 = return 1 fib n = do _ <- log $ "recursing when n = " ++ show n ++ "!" a <- fib (n-1) _ <- log $ "recursing again when n = " ++ show n ++ "!" b <- fib (n-2) return $ a + b -- fib :: Int -> State Log Int -- b) what is the type of example1 below? -- runState :: State s a -> s -> (a, s) example1 = runState (fib 4) initialLog where initialLog = Log Warn [] [] -- c) write a function 'withLevel' that takes a severity -- and a stateful computation that may log things, -- and runs the computation -- at the given log level. -- (and resets everything afterwards) -- withLevel :: Severity -> State Log a -> State Log a withLevel lvl comp = do oldLvl <- setSeverityLvl lvl x <- comp _lvl <- setSeverityLvl oldLvl return x setSeverityLvl :: Severity -> State Log Severity setSeverityLvl lvl = do Log oldLvl warns crits <- get -- (theLog :: Log) <- (get :: State Log Log) -- let Log oldLvl warns crits = theLog let newLog = Log lvl warns crits put newLog return oldLvl logTheCurrentSeverity :: State Log () logTheCurrentSeverity = do Log lvl _ _ <- get _ <- log $ "the current log level is: " ++ show lvl return () example2 = runState computation initialLog where initialLog = Log Warn [] [] computation = do logTheCurrentSeverity withLevel Critical $ do _ <- log "woei" logTheCurrentSeverity logTheCurrentSeverity -------------------------------------------------------------------------------- -- * TypeClasses & Monoids -- data Log = Log Severity -- Last severity used -- [String] -- the warnings -- [String] -- criticals -- deriving (Show) -- d) Make 'Log' an instance of 'Eq'; two logs are considered equal if -- and only if contain the same messages (in the same order). -- -- (so the current loglevel does not matter) -- instance Eq Log where Log _ warns crit == Log _ warns' crits' = warns == warns' && crit == crits' -- In the lecture I asked what would happen to this Eq instance if -- somehow Log had a type parameter 'a' the type of its warnings: -- data Log a = Log Severity -- Last severity used -- [a] -- the warnings -- [String] -- criticals -- deriving (Show) -- -- This would yield: -- -- instance Eq a => Eq (Log a) where -- Log _ warns crit == Log _ warns' crits' = warns == warns' -- && crit == crits' -- e) write a function that combines two Logs -- by combining their messages. Take the right Log level combineLogs :: Log -> Log -> Log combineLogs (Log _ warns crits) (Log lvl warns' crits') = Log lvl (warns <> warns') (crits <> crits') -- | In the latests versions of base, the standard Library, the Monoid typeclass is actually -- split into 'Monoid' that essentially only defines 'mempty', and Semigroup that defines -- the combining operation <> class Monoid m where -- | Unit element mempty :: m -- | Associative operation to combine two 'm' values into a single one (<>) :: m -> m -> m instance Monoid [a] where mempty = [] (<>) = (++) instance Monoid Log where mempty = Log Warn [] [] (<>) = combineLogs -- f) make Log an instance of Monoid; by default messages should be at level Warn --when combining logs; take the rightmost severity as the current severity. -- we can now write : example3 :: Log example3 = myLeftLog <> myRightLog where myLeftLog = Log Warn ["bla"] ["critical stuff here"] myRightLog = Log Critical ["foo"] ["more critical errors"] -- g) given a list of severity, String pairs, write a function that combines -- all messages into a single Log -- -- hint: you can use the function -- 'foldMap :: Monoid m => (a -> m) -> [a] -> m' logAll :: [(Severity,String)] -> Log logAll = foldMap singleton where singleton :: (Severity, String) -> Log singleton (lvl, msg) = addMsg msg $ Log lvl [] [] -- h) Our usage of Lists in the implementation of the 'Log' data type is rather poor. -- (why?) Implement Log using the Seq data type from Data.Sequence instead. -- i) using what you know about Monoids, how would you implement the function 'concatMap'? concatMap :: (a -> [b]) -> [a] -> [b] concatMap = foldMap -- what about an implementation that concatenates a bunch of Sequences (Seq a)'s ? concatMapSeq :: (a -> Seq b) -> [a] -> Seq b concatMapSeq = foldMap -------------------------------------------------------------------------------- -- * WHNF -- j) -- when is an expression in WHNF? -- 1. expr is a constructor of a data type -- 2. lambda function -- 3. partieel toegepaste functie (functie met te weinig args) -- k) evalute the following expressions to WHNF. -- -- argue why the resulting expresion is in WHNF -- -- write undefined if the function crashes -- map undefined [undefined, 5] -- map undefined (undefined : 5 : []) -- undefined undefined : map undefined (5 : []) -- foldr (:) [] (1:2:3:4:5:[]) -- 1 : (foldr (:) [] (2:3:4:5:[])) -- zip "blah" -- (undefined, 5) `seq` [0,1,2] -- (0:1:2:[]) -- foldr (&&) undefined [True,True] -- const (undefined,[1]) "blah" -- (undefined,[1]) -- (const (undefined,[1])) $! 5 -- const (undefined,[1]) 5 -- (undefind,[1]) -- Log undefined (map (++ ["woei"])) ["bla"] -- (1+foldr (+) 0 [1...10]) : map (+5) [undefined, 1, 0] -------------------------------------------------------------------------------- -- * Laws -- there are some laws: -- -- instances of Monoid should satisfy: -- -- Left identity: -- mempty <> x = x -- Right identity -- x <> memtpy = x -- Associativity -- x <> (y <> z) = (x <> y) <> z -- l) prove that our instance of Log indeed satisfies this law -- -- -- you may want to use/prove that (++) is associative (using induction on x) -- -------------------------------------------------------------------------------- -- * Helper stuff instance Monoid (Seq a) where mempty = Data.Sequence.empty (<>) = (Data.Sequence.><) foldMap _ [] = mempty foldmap f (x:xs) = f x <> foldMap f xs main = print $ example1