Search code examples
schemerackethigher-order-functionsfoldhtdp

How do I start defining map from fold?


I'm working through Htdp 2e, and have been given the problem of defining the map function from foldr or foldl. I'm not sure where to start.

Map takes in a function of one argument and a list. So I have defined my function similarly. Fold requires a function of two arguments, a base, and a list.

My issue is how do I take the one argument function of map and recreate it with a two argument function in fold?

The purpose of the problem is to teach how to create abstractions using higher order functions.

Some push in the right direction would be greatly appreciated

; [X Y] [X -> Y] [List-of-X] -> [List-of-Y]
; consumes a function and a list and applies f 
; to each item in the list

(define (map-from-fold f l)
    (foldr f base lx))

Solution

  • Think about the main difference between foldr and map:

    (map add1 '(1 2 3))  
    ; == (cons (add1 1) (cons (add1 2) (cons (add1 3) '())))
    
    (fold f '() '(1 2 3) 
    ; ==> (f 1 (f 2 (f 3 '())))
    

    Notice that f needs to cons as well as whatever function is added. Thus when you pass f to map the function that is passed to foldr needs to both cons the result of (f element) with the accumulator. Good luck!