Ch7 Quiz A
On this quiz you should demonstrate your understanding of Maybe
,
fold, and sort.
-
Write
q1clip :: Int -> Int -> Maybe Int
that takes in two numbersbottom
andk
, and puts outk
as long ask
is at leastbottom
. Otherwise outputNothing
. -
Is the following expression legal Haskell? Explain what is wrong or what it does.
explainit = q1clip 10
-
For the function
teen :: Maybe Int -> Maybe Int
, inputs from 11 through 19 produce nothing. Other numbers produce double their value. Nothing as an input produces an output of 15.Write
teen
.teen :: Maybe Int -> Maybe Int
-
The function
chain2
takes in two functionsg
andf
fromInt
toMaybe Int
and a numbern
. If both functions output aJust
, then the result should beJust (g (f n))
… except thatg(f(x))
is not technically legal because the types do not match up. Otherwise outputNothing
.In this question please demonstrate that you can use
let
orwhere
to make a local definition of some kind.chain2 :: (Int -> Maybe Int) -> (Int -> Maybe Int) -> Int -> Maybe Int chain2 g f n = undefined
Extended example:
f x | x < 0 = Nothing | otherwise = Just (x*x) g y | y > 100 = Nothing | otherwise = Just (-y) chain2 g f 5 == Just (-25) chain2 g f 11 == Nothing chain2 g f (-1) == Nothing
-
The
comparer
givesTrue
when both coordinates of the ordered pair have numbers that are at most 5 units from each other. In all other cases, it givesFalse
.comparer :: (Maybe Int, Maybe Int) -> Boolean
There is also a back side.
Fold and Sort
We are given a list of “tasks” to do. Each task has a positive integer indicating its priority (like 105) as well as a task description string (like “Eat Breakfast”).
type Task = (Int, String)
taskList :: [Task]
taskList = [(10,"Dust trophy"),
(116,"Mow the lawn"),
(120,"Get groceries")]
There are three general categories of task priorities:
- priorities at least 1000 are considered “critical”;
- priorities at least 100 are “high” priority;
- others are labeled “all”.
-
Given a list of tasks and a priority label string (“critical”, “high”, “all”), produce a list of tasks in the corresponding category in order from highest priority to lowest.
Humans are not good at assigning exact priorities, so consider two tasks to have equivalent priority if the priority numbers differ by 2 or less.
With two tasks of equivalent priority, sort alphabetically based on the task description (“A” comes early in the list; “Z” comes late.)
You have to use
sortBy
.taskFit :: [Task] -> String -> [Task] taskFit xs levelName = sortBy helpf $ ... more of your code ... xs
It is acceptable but not required to use
(helpf levelName)
instead ofhelpf
.Example:
taskFit taskList "High" == [(120,"Get groceries"), (116,"Mow the lawn")]
-
Count the number of tasks whose priority number is at least a certain priority cutoff. You have to use
foldl
. Writecth
.ct :: [Task] -> Int -> Int ct xs priorityCutoffNum = foldl cth 0 xs
It is acceptable but not required to use
(cth priorityNum)
instead ofcth
.check_ct = (ct taskList 116 == 2)