In my previous post I introduced yet another Lisp interpreter. When it was posted there was no support for macros.
Since I've recently returned from a visit to the UK, and caught COVID-19 while I was there, I figured I'd see if my brain was fried by adding macro support.
I know lisp macros are awesome, it's one of those things that everybody is told. Repeatedly. I've used macros in my emacs programming off and on for a good few years, but despite that I'd not really given them too much thought.
If you know anything about lisp you know that it's all about the lists, the parenthesis, and the macros. Here's a simple macro I wrote:
(define if2 (macro (pred one two)
`(if ~pred (begin ~one ~two))))
The standard lisp if
function allows you to write:
(if (= 1 a) (print "a == 1") (print "a != 1"))
There are three arguments supplied to the if
form:
- The test to perform.
- A single statement to execute if the test was true.
- A single statement to execute if the test was not true.
My if2
macro instead has three arguments:
- The test to perform.
- The first statement to execute if the test was true.
- The second statement to execute if the test was true.
- i.e. There is no "else", or failure, clause.
This means I can write:
(if2 blah
(one..)
(two..))
Rather than:
(if blah
(begin
(one..)
(two..)))
It is simple, clear, and easy to understand and a good building-block for writing a while
function:
(define while-fun (lambda (predicate body)
(if2 (predicate)
(body)
(while-fun predicate body))))
There you see that if the condition is true then we call the supplied body, and then recurse. Doing two actions as a result of the single if
test is a neat shortcut.
Of course we need to wrap that up in a macro, for neatness:
(define while (macro (expression body)
(list 'while-fun
(list 'lambda '() expression)
(list 'lambda '() body))))
Now we're done, and we can run a loop five times like so:
(let ((a 5))
(while (> a 0)
(begin
(print "(while) loop - iteration %s" a)
(set! a (- a 1) true))))
Output:
(while) loop - iteration 5
(while) loop - iteration 4
(while) loop - iteration 3
(while) loop - iteration 2
(while) loop - iteration 1
We've gone from using lists to having a while-loop, with a couple of simple macros and one neat recursive function.
There are a lot of cute things you can do with macros, and now I'm starting to appreciate them a little more. Of course it's not quite as magical as FORTH, but damn close!
Tags: forth, github, lisp
|