Mystery
Sadly, this is the last lecture. We hope you’ve enjoyed the show. Before you go, we have just one last trick to show you. Today we’ll talk about some topics that are close to our hearts.
A Taste of Lisp
This is the most beautiful program ever written. I encourage you to watch Will Byrd’s amazing talk on the same subject. I will be presenting a much abridged version. We’re going to write a Lisp interpreter in Lisp. But first, let’s learn some Lisp.
Atoms.
5 #t 'foo
Lists.
(list 5) (list 5 6) (list (list 5) 6)
Application.
(null? '()) (null? 5)
Quotation.
(quote 5) '(5 6) '(null? 5)
Abstraction.
+ (λ (x) x) ((λ (x) x) 5)
Binding.
(define foo 'bar) (define double (λ (x) (+ x x)))
Conditions.
(if (null? 5) 6 7) (match (list 3 4) [(list x y) (+ x y)])
Done.
Lisp in Lisp
We’re going to write a Lisp interpeter in Lisp. First a simple calculator interpreter as an appetizer.
(define eval-expr (λ (expr) (match expr [n #:when (number? n) n] [(list 'add1 e) (add1 (eval-expr e))] [(list '+ e1 e2) (+ (eval-expr e1) (eval-expr e2))])))
Fine, but this is boring. It isn’t Turing-complete. When’s the main course?
(define eval-expr (λ (expr env) (match expr ;; boring [n #:when (number? n) n] [(list 'add1 e) (add1 (eval-expr e env))] [(list '+ e1 e2) (+ (eval-expr e1 env) (eval-expr e2 env))] ;; fun [(list rator rand) ((eval-expr rator env) (eval-expr rand env))] [x #:when (symbol? x) (env x)] [(list 'λ (list x) body) (λ (arg) (eval-expr body (λ (y) (if (eq? x y) arg (env y)))))])))
I’m full, but if you aren’t you may want to have some dessert.
References
Learning about Lisp and interpreters is a life-long endeavor, but there are plenty resources to get started.