Skip to content

Instantly share code, notes, and snippets.

@ghoseb
Forked from jimweirich/church_numerals.clj
Created June 12, 2009 19:01
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 ghoseb/128842 to your computer and use it in GitHub Desktop.
Save ghoseb/128842 to your computer and use it in GitHub Desktop.
Church Numerals in Clojure
; Church Numerals in Clojure
;
; Church numerals use anonymous functions to represent numbers.
;
; ((zero f) x) -- returns x
; ((one f) x) -- return (f x)
; ((two f) x) -- return (f (f x))
; ...
(def zero (fn [f] (fn [x] x)))
(def one (fn [f] (fn [x] (f (((fn [f] (fn [x] x)) f) x)))) )
(def two (fn [f] (fn [x] (f (((fn [f] (fn [x] (f (((fn [f] (fn [x] x)) f) x)))) f) x)))) )
; incr increments church numeral n by return a function that applies f
; one more time than n.
(defn incr [n] (fn [f] (fn [x] (f ((n f) x)))))
; Here's an easy way to test if a church numeral is zero.
(defn zero-cn? [n] ((n (fn [x] false)) true) )
; Add two church numerals to produce a new church numeral.
(defn +cn [a b]
(fn [f] (fn [x] ((a f) ((b f) x)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment