/* Compute n! in functional style in C */
int functional_fact(int n) {
if (n == 0) return(1);
else return(n*functional_fact(n-1));
}
;; Compute n! in functional style in Scheme
(define functional-fact
(lambda (n)
(if (= n 0)
1
(* n (functional-fact (- n 1))))))
/* Compute n! in imperative style in C */
int imperative_fact(int n) {
int acc = 1;
while (n > 0) {
acc *= n;
n--;
}
return(acc);
;; Compute n! in imperative style in Scheme
(define imperative-fact
(lambda (n)
(letrec
((loop
(lambda (n acc)
(if (= n 0)
acc
(begin
(set! acc (* n acc)) ;; yukk
(set! n (sub1 n))
(loop n acc)
)))))
(loop n 1))))
/* Compute n! in C using tail-recursion */
int loop(int n, int acc) {
if (n == 0) return(acc);
else return(loop(n-1,n*acc));
}
int tail_recursive_fact(int n) {
return(loop(n,1));
}
;; Compute n! in Scheme using tail-recursion
(define tail-recursive-fact
(lambda (n)
(letrec
((loop
(lambda (n acc)
(if (= n 0)
acc
(loop (sub1 n) (* n acc))
))))
(loop n 1))))
/* Compute nth Fibonacci number in functional style in C */
int functional_fib(int n) {
if (n <= 1) return(n);
else return(functional_fib(n-1)+functional_fib(n-2));
}
;; Compute nth Fibonacci number in functional style in Scheme
(define functional-fib
(lambda (n)
(if (<= n 1)
n
(+ (functional-fib (- n 1)) (functional-fib (- n 2))))))
/* Compute nth Fibonacci number in C using tail-recursion */
int loop(int n, int acc1, int acc2) {
if (n == 0) return(acc1);
else return(loop(n-1,acc2,acc1+acc2));
}
int tail_recursive_fib(int n) {
return(loop(n,0,1));
}
;; Compute nth Fibonacci number in Scheme using tail-recursion
(define tail-recursive-fib
(lambda (n)
(letrec
((loop
(lambda (n acc1 acc2)
(if (= n 0)
acc1
(loop (sub1 n) acc2 (+ acc1 acc2))
))))
(loop n 0 1))))
/* Compute nth Fibonacci number in imperative style in C */
int imperative_fib(int n) {
int acc1, acc2, temp;
acc1 = 0;
acc2 = 1;
while (n > 0) {
temp = acc2; /* Need to use temp variable */
acc2 += acc1;
acc1 = temp;
n--;
}
return(acc1);
}
;; Compute nth Fibonacci number in imperative style in Scheme
(define imperative-fib
(lambda (n)
(letrec
((loop
(lambda (n acc1 acc2)
(if (= n 0)
acc1
(let ((temp acc2))
(set! acc2 (+ acc1 acc2)) ;; yukk
(set! acc1 temp)
(set! n (sub1 n))
(loop n acc1 acc2)
)))))
(loop n 0 1))))
tail.c
Assembly code generated for tail.c using gcc -O1
Assembly code generated for tail.c using gcc -O4