;;; File: ;;; churchnums.scm ;;; Author: ;;; Samuel A. Rebelsky ;;; Summary: ;;; A simple exploration of the Church numerals, written for ;;; students in CSC302 2006S. ;;; Discussion: ;;; The Church numerals are a relatively pure way of representing ;;; the integers within the lambda calculus. Every non-negative ;;; integer is written as a two-parameter function. Integer i ;;; applies the first parameter to the second i times. For ;;; example, ;;; * zero is \ s z . z ;;; * one is \ s z . s z ;;; * two is \ s z . s (s z) ;;; * three is \ s z . s (s (s z)) ;;; Note that each Church numeral can behave as a loop that ;;; runs that number times. For example, to write "hello" ;;; three times, we might write ;;; (three (lambda (x) (display "hello")) (newline)) ;;; Some constants. (define zero (lambda (s z) z)) (define one (lambda (s z) (s z))) (define two (lambda (s z) (s (s z)))) (define three (lambda (s z) (s (s (s z))))) ;;; Incrementing Church numerals. (define cinc (lambda (cn) (lambda (s z) (cn s (s z))))) ;;; Adding Church numerals ;;; What does it mean to add m and n? It means we increment ;;; n m times (or vice versa). (define cadd (lambda (m n) (m cinc n))) ;;; To multiply m by n, we add n to zero m times (define cmult (lambda (m n) (lambda (s z) (m (lambda (x) (n s x)) z)))) ;;; Building new Church numerals from old (define nine (cmult three three)) (define ten (cadd nine one)) (define hundred (cmult ten ten)) ;;; Converting Church numerals ; To convert a Church numeral to a list of ones, we ; want to cons a 1 for each s in the body and use ; the empty list for the zero case. (define cnum->oneslist (lambda (cn) (cn (lambda (n) (cons 1 n)) null))) (define cnum->int (lambda (cn) (cn (lambda (n) (+ n 1)) 0))) (define count (lambda (cn) (cn (lambda (x) (display x) (newline) (+ x 1)) 0)))