Thursday, July 17, 2003

Macros

I'm learning macros now. They take a little getting used to, but I've written a couple of them to recreate some control structures from other languages. First is the arithmetic-if from old FORTRAN.
(define-macro arith-if

(lambda (test-val neg-branch zero-branch pos-branch)
`(cond ((< ,test-val 0) ,neg-branch)
((= ,test-val 0) ,zero-branch)
((> ,test-val 0) ,pos-branch))))

Next is a for loop from Pascal or BASIC (without a step option).
(define-macro p-for

(lambda (counter start limit . body)
`(let loop ((,counter ,start))
(when (<= ,counter ,limit)
,@body
(loop (+ ,counter 1))))))

No comments: