Tuesday, 2 February 2010

macro hacking - while loop

common lisp code while construct from c language.
in small scale program , this seems to work ok .
reliant on behaviour return to escape inner loops , it seems to be working fine in sbcl so far.


(defpackage :test
(:use #:cl)
(:shadow #:while))

(in-package :test)

(defmacro while(condition &rest body)
`(progn
;; loop
(loop
;; check condition - if not met then exit loop
(if (not ,condition) (return))
;; insert body here...
,@body)))

;; tests

(let ((i 0))
(while (< i 10)
(format t "i= ~a~%" i)
(setq i (+ i 1))))
i= 0
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
i= 7
i= 8
i= 9
NIL


(let ((i 0) (j 0))
(while (< i 5)
(setq j 0)
(while (< j 5)
(format t "i= ~a j=~a~%" i j)
(setq j (+ j 1)))
(setq i (+ i 1))))

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

No comments:

Post a Comment