#! /bin/sh
exec ../src/sizzle -qs $0 $*
!#
;; test/scheme-art.scm -- tests using various algorithms
;;
;; The algorithm presented here is taken from the book `Scheme and the
;; Art of Programming' by George Springer and Daniel P. Friedman

;; Load the test framework.

(load "test-suite.scm")

(begin-section "fibonacci")

(begin-sub-section "recursive")

(define (fib n)
  (if (< n 2)
      n
      (+ (fib (- n 1)) (fib(- n 2)))))

(pass-if (fib 0) 0 =)
(pass-if (fib 1) 1 =)
(pass-if (fib 2) 1 =)
(pass-if (fib 3) 2 =)
(pass-if (fib 4) 3 =)
(pass-if (fib 5) 5 =)
(pass-if (fib 6) 8 =)
(pass-if (fib 7) 13 =)
(pass-if (fib 10) 55 =)
(pass-if (fib 20) 6765 =)

(begin-sub-section "iterative")

(define (fib-it n)
  (letrec ((fib-helper
	    (lambda (n acc1 acc2)
	      (if (= n 1)
		  acc2
		  (fib-helper (- n 1) acc2 (+ acc1 acc2))))))
    (if (zero? n)
	0
	(fib-helper n 0 1))))

(pass-if (fib-it 0) 0 =)
(pass-if (fib-it 1) 1 =)
(pass-if (fib-it 2) 1 =)
(pass-if (fib-it 3) 2 =)
(pass-if (fib-it 4) 3 =)
(pass-if (fib-it 5) 5 =)
(pass-if (fib-it 6) 8 =)
(pass-if (fib-it 7) 13 =)
(pass-if (fib-it 10) 55 =)
(pass-if (fib-it 20) 6765 =)

(begin-section "factorial")

(begin-sub-section "recursive")

(define (fact n)
  (if (zero? n)
      1
      (* n (fact (- n 1)))))

(pass-if (fact 0) 1 =)
(pass-if (fact 1) 1 =)
(pass-if (fact 2) 2 =)
(pass-if (fact 3) 6 =)
(pass-if (fact 4) 24 =)
(pass-if (fact 6) 720 =)

(begin-sub-section "recursive")

(define (fact-it n)
  (letrec ((fact-helper
	    (lambda (n acc)
	      (if (zero? n)
		  acc
		  (fact-helper (- n 1) (* acc n))))))
    (fact-helper n 1)))

(pass-if (fact-it 0) 1 =)
(pass-if (fact-it 1) 1 =)
(pass-if (fact-it 2) 2 =)
(pass-if (fact-it 3) 6 =)
(pass-if (fact-it 4) 24 =)
(pass-if (fact-it 6) 720 =)

(test-summary)
