-- runhaskell QA.hs -- -- QA for 2026 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 {- We will try to implement some sort of logging functionality by using a State monad; i.e. recall that 'State s a' is type that models computations that returns an 'a' while using some (internal) state of type 's'. So: -} foo :: State s a foo = undefined -- a computation that returns an 'a' while using some (internal) state of type 's' -- compare this to: bar :: i -> a bar = undefined -- a (pure) computation that takes an 'i' as input and produces an 'a' as output -- 'State s' is an instance of Monad, in addtion, we have the following two useful functions: -- 'get' is a computation that retrieves the current state s -- get :: State s s -- 'put sNew' is a computation that sets the current state to sNew -- put :: s -> State s () -- so we can for example implement: -- | 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') -- Recall that the 'Monad' typeclass is defined as follows: -- -- class Applicative m => Monad m where -- -- main two functions: -- return :: a -> m a -- (>>=) :: m a -> (a -> m b) -> m b -- -- it also has some additional functions, among which: -- (>>) :: m a -> m b -> m b -- ma >> mb = ma >>= \_ -> mb -- so we can desugar the Do-notation into using return, >>= (and >>) directly. -- -- -- a) Convert log to use >>=, return, and >> -- here is an example of a (stateful) computation thaty uses our logging functionality: -- | 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 -- b) what is the type of example1 below? -- you can use that: -- -- 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) -- -- hint: you may want to write the following helper function that -- given a Severity 'lvl' produces a computation that: 1) retrieves -- the current severity level 'oldLvl', sets the severity level to -- lvl, and then returns the old level. setSeverityLvl :: Severity -> State Log Severity setSeverityLvl = undefined withLevel :: Severity -> State Log a -> State Log a withLevel lvl comp = undefined ---------------------------------------- -- we can then write: 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 -- recall our Log data type -- 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) -- -- 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 = undefined -- | the 'Monoid' typeclass models types 'm' that have a unit element mempty and some -- combination operation <> that combines two 'm's into one. class Monoid m where -- | Unit element mempty :: m -- | Associative operation to combine two 'm' values into a single one (<>) :: m -> m -> m -- NOTE: 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 <> -- Fro example, Lists form a Monoid: instance Monoid [a] where mempty = [] (<>) = (++) -- 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 = undefined -- 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 = undefined -- what about an implementation that concatenates a bunch of Sequences (Seq a)'s ? concatMapSeq :: (a -> Seq b) -> [a] -> Seq b concatMapSeq = undefined -------------------------------------------------------------------------------- -- * WHNF -- j) -- when is an expression in WHNF? -- 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] -- foldr (:) [] (1:2:3:4:5:[]) -- zip "blah" -- (undefined, 5) `seq` [0,1,2] -- foldr (&&) undefined [True,True] -- const (undefined,[1]) "blah" -- (const (undefined,[1])) $! 5 -- 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 -- This instance is actually already available for the version of 'Monoid' that is in Base. 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