In this homework you will gain skills by working on two different tasks.
Study the notes we covered in class. This includes the presentation and the examples we defined in class. Then answer the following questions by writing a Haskell program.
A useful data type is called Maybe
data Maybe a = Nothing | Just a
It has two constructors Nothing and Just. It is often used when some input or result is optional or may or may not be possible. Pattern matching will have two clauses. For example a function that determines if the Just constructor is used might look like:
isJust Nothing = False isJust (Just x) = True
The maybe type is often used to indicate if something is possible. For example when given a list of pairs, one might search for the first pair where the first part of the pair is equal to some key, and return Just the second part of the pair if a matching pair is found. Note that sometimes no possible matching key is found, so that is when the Nothing constructor is returned.
(1) Write the lookup function with contract given below.
find :: key -> [(key,value)] -> Maybe valueBefore you begin be sure you.
data BinTree a = ...
(3) Using the constructor functions of BinTree: create 3 different trees of type BinTree Int. Recall the tree constructors are: Empty, One, and Branch. Be sure your trees vary in the number of Int elements are stored in your three example trees.
tree1,tree2,tree3:: BinTree Int tree1 = undefined tree2 = undefined tree3 = undefined
(4) Write two functions over BinTrees.
flatten:: (BinTree a) -> [a]The idea is to create a list of all the elements of type a in BinTree a.
and
CountTree:: (BinTree Int) -> IntThe idea is to sum up all the elemenets of type Int in a BintTree Int. If no elements appear return zero.
Before you begin be sure you.
Study the crib sheet 12 ways to create a function. Recall the source for this cribsheet can be found on the Haskell Resouce Sheet.
(5) Write the function plus5 three different ways. where (plus5 3) --> 8, (plus5 0) --> 5, etc.
plus5a :: Int -> IntUsing an anonymous function (lambda expression).
plus5b :: Int -> IntUsing a section.
plus5c :: Int -> IntUsing top level equations.
(6) Write functions smallest and largest (do not use the library functions min or max). Use guarded clauses for smallest and an if expression for largest.
smallest :: Ord t => t -> t -> t largest :: Ord t => t -> t -> t
(7) Write the function ncopies. Use a where clause and a comprehension.
ncopies:: Int -> a -> [a]