Ch6 Quiz B

Concepts

A fold function is a function that can be used in foldl. The function (+) can be used as a fold function. An example of this would be:

check = [ foldl (+) 0 [1..10] == 55 ]

The function reverse cannot be used as a fold function for several reasons; one of them is that it cannot use the initial value given.

  1. For each of these functions, explain whether or not it can be used for a “fold” function by foldl? Give an example using it (input and output) or explain why not.

    1. hawk :: [Int] -> Int

    2. snake :: [String] -> String -> [String]

    3. coyote :: Int -> [Int] -> Int

    4. lizard :: Float -> Float -> (Float, Float)

Short Answer

Explain whether or not the given function can do the job described directly by running some function on a given list. Do not consider the possibility of doing other things to the list before or after.

  1. map; find the squares of the even numbers in a list while getting rid of the odd numbers

  2. filter; find the largest number in a list

  3. foldl; given a list of numbers, make an ordered pair whose first item is a list of all of the items in a list in reverse order and whose second item is the total of all of the items in the list

Coding

  1. The Fibonacci numbers are defined recursively by $f(n) = f(n-1) + f(n-2)$ along with the $f(0)=0$ and $f(1)=1$. Fibonacci numbers are frequently needed in pairs, so define the function $pf(n)$ to be the ordered pair $\left(f(n), f(n+1)\right)$.

    Given a positive integer n, either write code that will use foldl to produce $pf(n)$ from the sequence [1..n] or explain why it is impossible.

    An answer (if it is possible) would look like this:

     pf n =  foldl ... [1..n]
     checks = [ pf 1 == (1,1), pf 2 == (1,2),
                pf 3 == (2,3), pf 4 == (3,5),
                pf 5 == (5,8) ]
    
  2. Write a function gda that finds the greatest positive difference between two adjacent numbers in a list. Use a fold as part of your function.

     examples = [gda [1,10] == 9,
                 gda [1,4,11] == 7,
                 gda [9,-3,5] == 12]
    
Last modified October 11, 2023: A quiz on map, filter, fold. (ac80551)