Skip to content

Instantly share code, notes, and snippets.

@atomictom
Created April 3, 2014 07:27
Show Gist options
  • Save atomictom/9949811 to your computer and use it in GitHub Desktop.
Save atomictom/9949811 to your computer and use it in GitHub Desktop.
#lang racket
; If a church numeral is like this: λf.λx.f(f(f...(f x))
; then just pass in 0 for 'x', and +1 for 'f' and for each 'f'
; we add one to x (0). So for no 'f's, we add 1 zero times and get
; 0. For 1 'f', we add 1 once and get 1, etc...
(define NUM
(lambda (n)
"Print a church numeral"
((n (lambda (x) (+ 1 x))) 0)))
; This is easy, if true selects the first item out of 2
; let the first be "true", and the second be "false"
; so it's like: λ(t="true").λ(f="false").(t or f)
(define BOOL
(lambda (bool)
"Print a boolean's value"
(display (format "~a\n" ((bool "true") "false")))))
; The only difference between these functions and the normal lambda calculus is
; that to do `(n f x)` you have to do `((n f) x)` if a function only takes one
; value at a time (ours do) but racket will try to apply all the parameters at once
(define SUCC
(lambda (n)
(lambda (f)
(lambda (x)
(f ((n f) x))))))
(define ZERO
(lambda (f)
(lambda (x)
x)))
(define ONE
(SUCC ZERO))
(define TWO
(SUCC ONE))
(define THREE
(SUCC TWO))
(define ADD
(lambda (m)
(lambda (n)
(lambda (f)
(lambda (x)
((m f) ((n f) x)))))))
(define MULT
(lambda (m)
(lambda (n)
(lambda (f)
(m (n f))))))
(define POW
(lambda (b)
(lambda (e)
(e b))))
(define TRUE
(lambda (t)
(lambda (f)
t)))
(define FALSE
(lambda (t)
(lambda (f)
f)))
(define AND
(lambda (p)
(lambda (q)
((p q) p))))
(display "\n--AND--\n")
(BOOL ((AND TRUE) TRUE))
(BOOL ((AND TRUE) FALSE))
(BOOL ((AND FALSE) TRUE))
(BOOL ((AND FALSE) FALSE))
(define OR
(lambda (p)
(lambda (q)
((p p) q))))
(display "\n--OR--\n")
(BOOL ((OR TRUE) TRUE))
(BOOL ((OR TRUE) FALSE))
(BOOL ((OR FALSE) TRUE))
(BOOL ((OR FALSE) FALSE))
(define NOT
(lambda (bool)
((bool FALSE) TRUE)))
(define IF
(lambda (condition)
(lambda (then)
(lambda (else)
((condition then) else)))))
(((IF TRUE) "true") "false")
(NUM ((ADD TWO) THREE))
(NUM ((POW ((ADD TWO) THREE)) ((MULT TWO) TWO)))
(BOOL (NOT FALSE))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment