fork download
  1. ;; We define our abstraction for zero
  2. (define zero 'D)
  3.  
  4. ;; Increment a number, i.e. get its successor
  5. (define (inc number)
  6. (cons 'P number))
  7.  
  8. ;; Decrement a number, i.e. get its predecessor
  9. (define (dec number)
  10. (cdr number))
  11.  
  12. ;; Adding two numbers is done by "shifting" from one to the other, one by one.
  13. ;; a + b = (a + 1) + (b - 1)
  14. (define (add lhs rhs)
  15. (if (eq? rhs zero)
  16. lhs
  17. (add (inc lhs) (dec rhs))))
  18.  
  19. ;; Multiplying the dumb way:
  20. ;; a * b = a + (a * (b - 1))
  21. (define (mul lhs rhs)
  22. (if (or (eq? rhs zero) (eq? lhs zero))
  23. zero
  24. (if (eq? rhs (inc zero))
  25. lhs
  26. (add lhs (mul lhs (dec rhs))))))
  27.  
  28. ;; Some values to play with
  29. (define one (inc zero))
  30. (define two (inc one))
  31. (define three (inc two))
  32. (define four (inc three))
  33.  
  34. ;; Display results
  35. (display one)(newline)
  36. (display two)(newline)
  37. (display (add one two))(newline)
  38. (display (mul two three))(newline)
  39. (display (mul three (mul three three)))(newline)
Success #stdin #stdout 0.04s 8616KB
stdin
Standard input is empty
stdout
(P . D)
(P P . D)
(P P P . D)
(P P P P P P . D)
(P P P P P P P P P P P P P P P P P P P P P P P P P P P . D)