2024 Review B
-
Write an implementation of
mapMaybe
, which keeps the “Just” results and throws away the “Nothing” results.ex1 = mapMaybe chop4 ["dog", "goldmedal", "fish"] check1 = (ex1 == ["medal"]) chop4 :: String -> Maybe String chop4 s | length s <= 4 = Nothing | otherwise = Just (drop 4 s)
-
Stone age functions use pattern matching and recursion, but not list comprehensions or any of the “fancy” machinery. Where possible, they even avoid guards and if statements.
Write a Stone Age implementation of
reverse
. Try to avoid using the++
operator. Stone age definitely means you should not useinit
orlast
. (Instead of re-implementing all of the tools you want to use, look for a simpler way using a helper function.) -
The class definition for
Semigroup
looks like this:class Semigroup c where (<>) :: c -> c -> c
You want to make the following into an instance of semigroup with addition in the first component and multiplication in the second.
data WorkerL w = WorkerR w w deriving (Show, Eq)
Actually you can only do this with a numerical type for
w
. -
(
gcfl
) One classic Advent of Code problem is to multiply the first and last numbers hidden in a string of “garbage”. For example, given theex3
below, the numbers are 123, 45, 678 and 9, so the answer would be123*9
, which is1107
.ex3 = "garbage123xyz45truck678dark9day" check3 = (gcfl ex3 == 123 * 9)
Write
gcfl :: String -> Integer
. -
What is the type signature, including common typeclasses, for each of these?
-
last
-
sum
-
replicate
-
Average, as defined below.
average xs = (sum xs) / (fromIntegral len) where len = length xs
-
Revjoin:
revjoin xs ys = (xs ++ [last xs / last ys] ++ ys)
-
-
Write the data definition for:
-
a
School
, which is just like aString
-
a
Studious
, includinghrs
for a decimal number of hours studied,sch
for the school they attend, andfd
for their main field of interest. -
(
schrs
) Write a signature and the function to find the total number of hours the students at each school study. The output should be a list of(School, Double)
.