Tuesday, 2 February 2010

macro hacking - repeat construct from logo

here we try to reproduce the repeat construct found in logo programming language.
logo would have repeat N [ ... ] , we would write maybe (repeat i N ...
where i holds number of iterations body has executed so far.
macro does pollute namespace though , test i after repeat statement run, find i variable has a value. not sure if this is a good thing or not.
maybe could of used a let construct.??


;;
(defpackage :test
(:use #:cl)
(:shadow #:repeat))

(in-package :test)

(defmacro repeat(symbol iterations &rest body)
`(progn
;;initialize
(setq ,symbol 0)
;; loop
(loop
;; check condition - if not met then exit loop
(if (>= ,symbol ,iterations) (return))
;; insert body here...
,@body
;; increment
(setq ,symbol (+ ,symbol 1)))))

;; tests

;; escape repeat loop use return
(repeat i 10 (if (= i 3) (return 'done)) (format t "i = ~a ~%" i))
i = 0
i = 1
i = 2
DONE

;; seems to work ok
(repeat i 5 (repeat j 5 (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

No comments:

Post a Comment