Practice Problems for Exam 2
Consider the following code:
conv :: Char -> Maybe Int conv c | isDigit c = Just (digitToInt c) | otherwise = NothingWhat are the types of variables/expressions in the code?Variable/Expression Type cisDigit cdigitToIntdigitToInt cJust (digitToInt c)Nothingconv cWrite a Haskell action
processNumber :: IO () using do notation that:- Prompts the user with "Enter an integer: " (without a trailing newline).
- Reads a line of input from the user.
- Computes (n2) + 2n for the entered integer n.
- Prints "Result: " followed by the computed value and a newline.
(read nstr :: Int)Functors (fmap)
What does the Haskell expression fmap (\x -> x * 2 + 1) [1, 2, 3] evaluate to?
- [2,4,6]
- [3,4,5]
- [1,3,5]
- [3,5,7]
Given
data Tree a = Leaf a | Node (Tree a) (Tree a)
What does the Haskell expression fmap length (Node (Leaf "hi") (Leaf "haskell")) evaluate to?- [2,7]
- Node (Leaf 2) (Leaf 8)
- Leaf 9
- Node (Leaf 2) (Leaf 7)
Given
inc :: Functor f => f Int -> f Int inc = fmap (+ 1)
What does the Haskell expression inc (Node (Leaf 1) (Leaf 2)) evaluate to?- Node (Leaf 1) (Leaf 2)
- Leaf 5
- Node (Leaf 2) (Leaf 2)
- Node (Leaf 2) (Leaf 3)
Given
data Tree a = Leaf a | Node (Tree a) (Tree a)
with its Functor instance, what does(fmap . fmap) (\n -> replicate n "!") [Leaf 1, Node (Leaf 2) (Leaf 0)]
evaluate to?- [Leaf "!", Node (Leaf "!!") (Leaf "")]
- [Leaf ["!", "!"], Node (Leaf ["!"]) (Leaf [])]
- [Leaf ["!"], Node (Leaf ["!", "!"]) (Leaf ["!"])]
- [Leaf ["!"], Node (Leaf ["!", "!"]) (Leaf [])]
Applicatives (<*>)
What does pure (+) <*> Just 4 <*> Nothing evaluate to?
- Just 0
- Just 4
- Just (+ 4)
- Nothing
What does [(+ 1), (* 2)] <*> [3, 5] evaluate to?
- [4, 6, 10, 6]
- [6, 10, 4, 6]
- [4, 10]
- [4, 6, 6, 10]
What does [] <*> [1, 2, 3] evaluate to?
- [Nothing, Nothing, Nothing]
- []
- [1, 2, 3]
- [0, 0, 0]
What does pure (\x y z -> x + y * z) <*> Just 2 <*> Just 3 <*> Just 4 evaluate to?
- Just 14
- Just 20
- Just 9
- Just 24
What does (pure (+ 1) <*> Just 2) <*> Just 3 evaluate to?
- Nothing
- Just 6
- Type error
- Just 5
Monads (>>=)
Given
safediv :: Int -> Int -> Maybe Int safediv _ 0 = Nothing safediv n m = Just (n div m)What does Just 20 >>= (\v1 -> Just 0 >> (\v2 -> safediv v1 v2)) evaluate to?
- Nothing
- Just 20
- Exception
- Just 0
Using the list Monad instance
xs >>= f = [ y | x <- xs, y <- f x ]What does [1, 2] >>= (\x -> [x, x * 10]) evaluate to?
- [11, 22]
- [[a, 10], [2, 20]]
- [1, 2, 10, 20]
- [1, 10, 2, 20]
Given
conv :: Char -> Maybe Int
conv c | isDigit c = Just (digitToInt c)
| otherwise = Nothing
What does conv '3' >>= (\a -> conv 'x' >>= (\b -> Just (a + b)))
evaluate to?
- Nothing
- Just 0
- Just 123
- Just 3
By the left identity law
return x >>= f = f xWhat does return 5 >>= (\n -> if n > 3 then Just (n * 2) else Nothing) evaluate to?
- Just 10
- Just 5
- 10
- Nothing
Using join mmx = mmx >> id over Maybe, what does Just (Just 7) >> id evaluate to?
- Just 14
- Just 20
- Just 11
- Just 24