; Various ways to implement the factorial function ; If using GNU Guile uncomment the following: ; (use-modules (srfi srfi-1)) ; (define foldl fold) ; The standard recursive factorial (define fact1 (lambda (n) (if (= n 0) 1 (* n (fact1 (- n 1)))))) (fact1 5) (fact1 100) ; We can modify this to be tail recursive (define tfact (lambda (n m) (if (= n 0) m (tfact (- n 1) (* n m))))) (define (fact2 n) (tfact n 1)) (fact2 5) (fact2 100) ; Alternatively, a "named" let is commmon when writing tail recursive ; functions. For example, here is another tail recursive factorial. (define fact3 (lambda (n) (let tfact ((n n) (m 1)) (if (= n 0) m (tfact (- n 1) (* m n)))))) (fact3 5) (fact3 100) ;; enumerate a list from n downto 1 (define enum-to-1 (lambda (n) (if (= 0 n) '() (cons n (enum-to-1 (- n 1))) ))) ;; factorial using a foldl over a list from n..1 (define fact4 (lambda (n) (let ((lst (enum-to-1 n))) (foldl * 1 lst)))) (fact4 5) (fact4 100)