;; The length of list L (define (length L) (if (eqv? L '()) 0 (+ (length (cdr L)) 1))) ;; How do you do this tail-recursively? (define (length L) ;; The length of list P plus the integer n. (define (length+ P n) (if (null? P) n (length+ (cdr P) (+ n 1)))) (length+ L 0)) ;; Assumes f is a two-argument function and L is a list. If L is (x1 x2...xn), ;; the result applying f n-1 times to give (f (f (... (f x1 x2) x3) x4) ...). ;; If L is empty, returns f with no arguments. (Simply Scheme version). (define (reduce f L) (define (reduce-tail so-far L) (if (null? L) so-far (reduce-tail (f so-far (car L)) (cdr L)))) (if (null? L) (f) (reduce-tail (car L) (cdr L)))) (define (map1 f L) (define (map1-tail results rest) (if (null? L) (reverse results) (map1-tail (cons (f (car rest))) (cdr rest))))) ;;; Assumes f is a k-argument function and L is a list of equal-length ;;; lists, L1...Ln. Returns the list ((f x11 x21 ...) ... (f x1n ...)), where ;;; xij is item j of list i. (define (map f . L) (define (map-tail results rest) (if (null? (car rest)) (reverse results) (map-tail (cons (apply f (map1 car L)) results) (map1 cdr L)))) (map-tail '() L))