More List Operations
Exercise 1
WriteafunctionunMaybethattakesalistofMaybe a,andreturnsalistcontainingtheelements.
Any Nothing’s present in the original list should be discarded. You will have to work out the type declaration. Make it as general as possible.
> unMaybe [Just 1, Nothing, Just 2]
[1,2]
> unMaybe [Nothing, Just ”hello”, Just ”world”] [”hello”,”world”]
Exercise 4
If one list has more elements than the other, just add the rest of the non-empty list to the end. >riffle [1,2,3] [4,5,6]
[1,4,2,5,3,6)
>riffle [1,2,3) [18,28,30,48,50,68)
(1,10,2,30,3,30,40,50,60)
>riffle [‘h’,’s’, ‘e’,’l’, ‘l’] [‘a’,’k’]
“haskell” Exercise 6
repeatApply takes 3 inputs:
• A fJnction f, with the same input and output type.
• Anintegern,indicatingthenumberoftimestoapplythefunction. • An element x with suitable type to insert into the function.
Output is the result of applying the function f to x, n many times. (So if n=3, the output should be f(f(f(x))). Applying f zero many times just returns x unchanged.) Make the type as general as can be.
Write a function that takes two lists and performs a ‘riffle” shuffle, alternating back and forth to return all elements from both lists.
I Write the repeatApply function. >repeatApply (*2) 3 1
8>repeatApply ( ++ ” NO “) 5 “OH” “OH NO NO NO NO NO”
Implement positiveSum, average, magnitude, dot using higher order functions.
positiveSum :: [Integer] -> Integer
Computes the sum of only the positive numbers in the list, ignoring negative numbers.
>positiveSum [1,-2,3] 4
average :: [Double] -> Double
Computes the average of a list of Double. The average of the collection {x1, x2 ,••• , xn } is defined to
be x1+zz+…+z..-J
magnitude : : [Double] -> Double
Computes the magnitude of a vector, represented as a [Double). Magnitude of a vector is defined as
X1
x� + x� +… + x� (Hint: You will need the sqrt function, which computes square dot :: [Double] -> [Double] -> Double
Computes the dot product of two vectors, represented by [Double]. The dot product is defined as
X1 Yt
X2 Y2
Yn
=✓
Xn
roots.)