; Folding ; is an extension of the idea of writing generic procedures like we ; did in the previous lab ; With folding, we will be even more ambitious and try to write a generic procedure ; for recursion with lists, and one for recursion with integers ; let us start off with a Factorial, which calculates the production of the ; postive integers less than or equal to the input, and we define 0! to be 1 (define factorial (lambda (n) (if (zero? n) 1 (* n (factorial (- n 1)))))) ; We want to write a generic version of recursion with integers ; so what are the things in the above definition that are specific to factorial? ; the "base-case-value" 1 and the "combiner" function * are the two things ; that are specific to factorial ; generic recursion with integers procedure, we call it FOLD-NATURAL (define fold-natural (lambda (base-case-value combiner) ; we want to write a block of code which returns a procedure ; we use letrec, because it will create a procedure that we can return (letrec ((recurrer (lambda (n) (if (zero? n) base-case-value (combiner n (recurrer (- n 1))))))) recurrer) )) (define factorial2 (fold-natural 1 *)) ; unfortunately this is not completely generic and will not be useful for ; writing Fibonacci ; recall two-power computes 2 to the power of the input number (define two-power (fold-natural 1 ; this lambda takes in n and (recurrer (- n 1)) ; and returns (* 2 (recurrer (- n 1))), which ; will give us 2 to the nth power (lambda (n recursive-result) (* 2 recursive-result)))) ; it may be useful to compare this to a more straightforward definition of ; two-power (define two-power (lambda (n) (if (zero? n) 1 (* 2 (two-power (- n 1))))))