Skip to content

Instantly share code, notes, and snippets.

@ashton314
Last active February 23, 2021 20:25
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 ashton314/ca86b5abc6c6a2ffb9eff78beb174350 to your computer and use it in GitHub Desktop.
Save ashton314/ca86b5abc6c6a2ffb9eff78beb174350 to your computer and use it in GitHub Desktop.
Showing how you can build a lambda calculus in 7 lines of Racket (that's the first function)
#lang racket
;; Demonstration of a turing-complete language
(define (ev e [ρ '()])
(match e
[(? symbol? x) (cadr (assoc x ρ))]
[`(λ (,xs ...) ,es) `(cls ,ρ ,xs ,es)]
[`(,f ,as ...)
(match (ev f ρ)
[`(cls ,cρ ,xs ,es) (ev es (append (map list xs (map (λ (v) (ev v ρ)) as)) cρ ρ))])]))
;; Run like this:
;; (ev '... expression to evaluate ...)
;; (ev '((λ (x) (x x) (λ (y) (y y)))) => loops forever
;; (ev '((λ (x) x) (λ (y) y))) => #<closure y y>
;; Add math to make things a little more interesting
(define (prim-op? s) (assoc s `((+ ,+) (- ,-) (/ ,/) (* ,*))))
(define (ev+ e [ρ '()])
(match e
[(? number? x) x]
[(? symbol? x) (cadr (assoc x ρ))]
[`(λ (,xs ...) ,es) `(cls ,ρ ,xs ,es)]
[`(,(? prim-op? op) ,as ...) (apply (cadr (prim-op? op)) (map (λ (v) (ev+ v ρ)) as))]
[`(,f ,as ...)
(match (ev+ f ρ)
[`(cls ,cρ ,xs ,es) (ev+ es (append (map list xs (map (λ (v) (ev+ v ρ)) as)) cρ ρ))])]))
;; (ev+ '((λ (x) (+ x 1)) 1)) => 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment