Created
April 6, 2021 04:17
-
-
Save kmicinski/3be14ef78f5326032ee4243941485b67 to your computer and use it in GitHub Desktop.
Church numerals in Racket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
;; numbers are represented as: | |
;; (lambda (f) (lambda (x) (f ... (f x)))) | |
;; where there are n calls to f. | |
(define zero (lambda (f) (lambda (x) x))) | |
(define one (lambda (f) (lambda (x) (f x)))) | |
(define two (lambda (f) (lambda (x) (f (f x))))) | |
;; do add1 n times, starting from 0 | |
;; (add1 (add1 ... (add1 0) ...)) | |
(define (church->nat n) | |
((n add1) 0)) | |
(define succ | |
;; the *argument* | |
(lambda (n) | |
;; the thing we're *returning* should do f "n+1 times" | |
;; ((n f) x) "applies f n times" and returns a result | |
;; | |
(lambda (f) (lambda (x) (f ((n f) x)))))) | |
(define plus | |
(lambda (n) | |
(lambda (k) | |
(lambda (f) (lambda (x) ((k f) ((n f) x))))))) | |
(define mult | |
(lambda (n) | |
(lambda (k) | |
(lambda (f) (lambda (x) (((n k) f) x)))))) | |
(displayln (format "we computed ~a" (church->nat ((plus two) two)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a minor mistake in this piece of code. The function defined as mult is actually k to the power n. The actual code: