Tuesday, 2 February 2010

macro hacking - a simple for loop

first attempt at writing c like for loop construct in common lisp. macros are supposed to be very powerful , so thought try to write my own and see if can tame this beast.

;;
(defpackage :test
(:use #:cl)
(:shadow #:for))
(in-package :test)

(defmacro for( symbol init cond inc &rest body)
`(progn
;;initialize
(setq ,symbol ,init)
;; loop
(loop
;; check condition - if not met then exit loop
(if (not ,cond) (return))
;; insert body here...
,@body
;; increment
(setq ,symbol ,inc))))


and some quick tests

;; quick test
(for i 0 (< i 5) (+ i 1) (format t "i = ~a ~%" i))
i = 0
i = 1
i = 2
i = 3
i = 4
NIL

(for i 0 (< i 5) (+ i 1)
(for j 0 (< j 5) (+ j 1)
(format t "i = ~a j =~a ~%" i j)))
i = 0 j =0
i = 0 j =1
i = 0 j =2
i = 0 j =3
i = 0 j =4
i = 1 j =0
i = 1 j =1
i = 1 j =2
i = 1 j =3
i = 1 j =4
i = 2 j =0
i = 2 j =1
i = 2 j =2
i = 2 j =3
i = 2 j =4
i = 3 j =0
i = 3 j =1
i = 3 j =2
i = 3 j =3
i = 3 j =4
i = 4 j =0
i = 4 j =1
i = 4 j =2
i = 4 j =3
i = 4 j =4
NIL


seems okay .
think try some more things like repeat construct in logo.

No comments:

Post a Comment