— Solution to Midterm #1 2019
— (Or the Haskell to generate the solution)
module Mid12019 where
— Question 1
dw _ [] = []
dw p (h:t)
| p h = dw p t
| otherwise = (h:t)
— dw (>2) [7,3,1,4,1,2,1]
— dw (/= ‘ ‘) “CS312? Real fun?”
— Question 2
— char2dig ch gives the digit for character ch (assuming it is a digit)
ch2dig :: Num t => Char -> t
ch2dig ch = fromIntegral (fromEnum ch – fromEnum ‘0’)
isdigit :: Char -> Bool
isdigit ch = ch >= ‘0’ && ch <= '9'
rdint:: Integer -> String -> (Integer, String)
— rdint takes two arguments, an integer and a string and returns a pair of an integer and a string
rdint n [] = (n,””)
rdint n (h:t)
| isdigit h = rdint (n*10+ch2dig h) t
| otherwise = (n,h:t)
— Question 3
myfilter c lst = foldr (\ e r -> if c e then e:r else r) [] lst
— myfilter (>3) [4,2,7,3,1,8]
dod p lst = foldr (\x y -> x : p x : y) [] lst
— dod (*10) [1..5]
— Question 4
— Lazy evaluation computes each argument (at most) once but call by name may compute an argument multiple times
— Sum is a function that takes in a list of some type and returns a value of that type, where the type is in the Num class
— Question 5
— myunc is the built-in uncurry function
myunc f (x,y) = f x y
calc:: String -> Integer
calc st = myunc calcin (rdint 0 st)
calc2 st = calcin n r
where (n,r) = (rdint 0 st)
calcin:: Integer -> String -> Integer
calcin n [] = n
calcin n (‘+’:r) = calcin (n+v) t where (v,t) = rdint 0 r
calcin n (‘-‘:r) = calcin (n-v) t where (v,t) = rdint 0 r
— Solution:
calcin2:: Integer -> String -> Integer
calcin2 n [] = n
calcin2 n (‘+’:r) = calcin2 (n+v) t where (v,t) = rdint 0 (dw (==’ ‘) r )
calcin2 n (‘-‘:r) = calcin2 (n-v) t where (v,t) = rdint 0 (dw (==’ ‘) r )
calcin2 n (‘ ‘:r) = calcin2 n r
— Or a simpler solution someone gave in their exam:
calcin3:: Integer -> String -> Integer
calcin3 n [] = n
calcin3 n (h:’ ‘:r) = calcin3 n (h:r)
calcin3 n (‘+’:r) = calcin3 (n+v) t where (v,t) = rdint 0 r
calcin3 n (‘-‘:r) = calcin3 (n-v) t where (v,t) = rdint 0 r
calcin3 n (‘ ‘:r) = calcin3 n r