;; folding over a list ;; How are foldl and foldr different? ;; To see how, you have to implement them. ;; To implement them, you have to understand ;; what they are doing! ;; ;; (foldl f base (list x_1 ... x_n)) = (f x_n ... (f x_1 base)) ;; (foldr f base (list x_1 ... x_n)) = (f x_1 ... (f x_n base)) ;; foldl is a higher-order function that processes a list ;; left-to-right, applying the function f repeatedly (define foldl (lambda (f b lst) (if (null? lst) b (foldl f (f (car lst) b) (cdr lst))))) ;; note the order of args to f ;; HOMEWORK QUESTIONS: ;; 1. Is foldl tail recursive? Explain why or why not? ;; 2. Is foldr tail recursive? (define foldr (lambda (f b lst) (if (null? lst) b (f (car lst) (foldr f b (cdr lst)))))) ;; standard recursive version of length of a list (define len (lambda (lst) (if (null? lst) 0 (+ 1 (len (cdr lst)))))) ;; length of a list implemented using foldl ;; note the order of the arguments to the ;; "anonymous" function passed as the first ;; argument to the foldl function. "_" means ;; don't care about the first argument. (define flen (lambda (lst) (foldl (lambda (_ n) (+ n 1)) 0 lst))) (define (sum ls) (foldl + 0 ls)) (define (prod ls) (foldl * 1 ls)) ;; non-tail recursive factorial (define fact (lambda (n) (if (zero? n) 1 (* n (fact (- n 1)))))) ;; enumerate a list from n downto 1 (define enumerate (lambda (n) (if (zero? n) '() (cons n (enumerate (- n 1))) ))) ;; factorial using foldl (define (fact n) (prod (enumerate n)))