Higher-order functions

Some exercises have answers and some don't. If you'd like an answer for any that don't have one, let us know. We'll add them as time permits.

  1. Rewrite

    ord $ chr $ ord $ chr $ ord 'x'
    
    to use parentheses instead of the application operator ($).
    ord (chr (ord (chr (ord 'x'))))
    
  2. At a glance you might get the impression that . (composition) and $ are equivalent. For example, some will think that

    ord $ chr $ ord $ chr $ ord 'x'
    
    can be rewritten as
    ord . chr . ord . chr . ord 'x'
    
    but it doesn't work. (Try it!)

    Add parentheses to the composition to make it work.

    (ord . chr . ord . chr . ord) 'x'
    
  3. What is something that's always true about the composition operator (.) that's only sometimes true about the $ operator?

    Composition always produces a function.
  4. Using the style shown in the slides, write out the calls to : that result from the following:

    > foldr (:) [100] [1..5]
    [1,2,3,4,5,100]
    
    > (:) 5 [100]
    [5,100]
    
    > (:) 4 it
    [4,5,100]
    
    > (:) 3 it
    [3,4,5,100]
    
    > (:) 2 it
    [2,3,4,5,100]
    
    > (:) 1 it
    [1,2,3,4,5,100]
    
  5. Repeat the previous question but with foldl (:) [100] [1..5].

  6. Cook up a far-fetched folding. (Search the slides for "refrigerators".) Mail it to us and we'll add it to the answers. If you don't want to be cited as the author, say so.

    None yet! :(
  7. write an expression of the form
         $     
    
    that produces a function.
    > head $ [head]
    <function>
    
    Simpler:
    > id $ head
    <function>
    
  8. Show a transcript of interaction with ghci with examples of foldings like these:
    • A list of Bools can be folded into a String.
    • A list of Ints can be folded into a Bool.

  9. Create a solution for street without writing any recursive functions. (Yes, sort of a big exercise, but a great one to work through as a group exercise with friends!)