;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "reader.ss" "plai" "lang") ; This demonstrates one way of implementing Scheme's MAP utility procedure, ; which thereby demonstrates the utility of the built-in APPLY procedure. ; ; Morgan McGuire, morgan@cs.williams.edu ; Given a list of lists, returns a list of all of the firsts ; ; get-firsts : list(list(?)) -> list(?) (define (get-firsts lists) (if (null? lists) ; We've processed all the lists '() (cons (first (first lists)) (get-firsts (rest lists))))) ; get-rests : list(list(?)) -> list(list(?)) (define (get-rests lists) (if (null? lists) '() (cons (rest (first lists)) (get-rests (rest lists))))) ; Re-implementation of Scheme's map procedure, to show how APPLY ; can be used. ; ; MAP : PROC x list( something )* -> list( something else) ; ; More formal typing: ; ; MAP : (A1 ... An -> B) x list(A1) x ... x list(An) -> list(B) ; (define (MAP proc . args) (if (null? (first args)) ; The lists are empty, so we're done '() ; Apply proc to the first of every arg (let* ([all-firsts (get-firsts args)] [all-rests (get-rests args)] [new-val (apply proc all-firsts)]) (cons new-val (apply MAP (cons proc all-rests)))))) (MAP + '(1 2 3) '(0 5 2))