Skip to content

Instantly share code, notes, and snippets.

@scudelletti
Last active December 10, 2018 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scudelletti/dd8aa8b4746d70fd501a8a8ac360da5e to your computer and use it in GitHub Desktop.
Save scudelletti/dd8aa8b4746d70fd501a8a8ac360da5e to your computer and use it in GitHub Desktop.
Numbers in Lambda Calculus - Following Destroy All Software approach
;; Church Numbers
(setq zero (lambda (f) (lambda (x) x)))
(setq one (lambda (f) (lambda (x) (funcall f x))))
(setq two (lambda (f) (lambda (x) (funcall f (funcall f x)))))
;; Manual Calc
(funcall (funcall zero (lambda (x) (+ 1 x))) 0)
(funcall (funcall one (lambda (x) (+ 1 x))) 0)
(funcall (funcall two (lambda (x) (+ 1 x))) 0)
;; Calc Function
(setq calc (lambda (f) (funcall (funcall f (lambda (x) (+ 1 x))) 0)))
(funcall calc zero)
(funcall calc one)
(funcall calc two)
;; Successor - Add 1
(setq succ (lambda (n) (lambda (f) (lambda (x) (funcall f (funcall (funcall n f) x))))))
(funcall calc (funcall succ zero))
(funcall calc (funcall succ one))
(funcall calc (funcall succ two))
;; Defining Three using succ function
(setq three (funcall succ two))
(funcall calc three)
require 'irb'
CONVERT = -> (x) { x + 1 }
ZERO = -> (f) { -> (x) { x } }
ONE = -> (f) { -> (x) { f.(x) } }
TWO = -> (f) { -> (x) { f.(f.(x)) } }
THREE = -> (f) { -> (x) { f.(f.(f.(x))) } }
FOUR = -> (f) { -> (x) { f.(f.(f.(f.(x)))) } }
FIVE = -> (f) { -> (x) { f.(f.(f.(f.(f.(x))))) } }
SIX = -> (f) { -> (x) { f.(f.(f.(f.(f.(f.(x)))))) } }
SEVEN = -> (f) { -> (x) { f.(f.(f.(f.(f.(f.(f.(x))))))) } }
EIGHT = -> (f) { -> (x) { f.(f.(f.(f.(f.(f.(f.(f.(x)))))))) } }
NINE = -> (f) { -> (x) { f.(f.(f.(f.(f.(f.(f.(f.(f.(x))))))))) } }
IDENTITY = -> (x) { x }
ADD1 = -> (n) { -> (f) { -> (x) { f.(n.(f).(x)) } } }
ADD = -> (n) { -> (m) { n.(ADD1).(m) }}
MULT = -> (n) { -> (m) { n.(->(acc) { ADD.(m).(acc) }).(ZERO) }}
#puts ADD1.(TWO).(CONVERT).(0)
#puts ADD.(TWO).(FIVE).(CONVERT).(0)
#puts MULT.(SEVEN).(THREE).(CONVERT).(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment