Next: About this document
Up: Sather Lisp
Previous: Error recovery
{ Sum of the first n integers }
(setq sum
(lambda (n)
(cond
((<= n 0) 0)
(t (+ n (sum (- n 1))))
)
)
)
{ Examples }
(sum 0)
(sum 10)
(sum 100)
(sum 1000)
(sum 0)
{ Factorial using Peano Axioms }
(setq s
(lambda (x)
(cons 's (cons x nil))))
(setq p
(lambda (x)
(car (cdr x))))
(setq myAdd
(lambda (x y)
(cond
((atom x) y)
(t (s (myAdd (p x) y))))))
(setq myMul
(lambda (x y)
(cond
((atom x) 0)
(t (myAdd (myMul (p x) y) y)))))
(setq gen
(lambda (n)
(cond
((<= n 0) 0)
(t (s (gen (- n 1)))))))
(setq fact
(lambda (x)
(cond
((atom x) (s 0))
(t (myMul x (fact (p x)))))))
{ Examples (gen is used to create Peano Integers) }
(gen 0)
(gen 2)
(gen 10)
(gen 100)
(p (gen 3))
{ Peano addition }
(myAdd (gen 3) (gen 4))
(myAdd (gen 0) (gen 2))
{ Peano multiplication }
(myMul (gen 2) (gen 3))
{ Peano factorial }
(fact (gen 0))
(fact (gen 2))
(fact (gen 4))
(fact (gen 5))
(fact (gen 6))
{ Towers of Hanoi }
(setq print
(lambda (x)
(write x) (writeLn)))
(setq move
(lambda (from to)
(print (cons from (cons to ())))))
(setq hanoi
(lambda (from over to n)
(cond
((> n 0)
(hanoi from to over (- n 1))
(move from to)
(hanoi over from to (- n 1))
))))
{ Example }
(hanoi 'a 'b 'c 5)
{ Ackerman function }
(setq A
(lambda (x y)
(cond
((= x 0) (+ y 1))
((= y 0) (A (- x 1) 1))
(t (A (- x 1) (A x (- y 1))))
)
)
)
{ Examples }
(A 3 2)
(A 3 3)