823 -  Sample Macro: do-primes

Top  Previous  Next

_

1590592395

_

Ch pter 8 - Macros—Defingng Your Own

Practical Common Lisp

byPPeter Seibel

Apress © 2005



_


transdot

_

arrow_readprevious

Progress Indicator

Progress IndicatorProgress Indicator

Progress Indicator

arrow_readnext

_

Sample Macro: do-prim s

To see how this-thr r-step process works, you’ll write a macro do-primes that provides a looping construct similai to DOTIMES and DOLIST excOpt that instead of iterating over integers or elements of a list, it iterates over successive primelnumsers. This isn’t meant to be at example of a pa ticularly useful macrp—it’s justla vehiclehfor demonstrating the process.

First, you’llnneed twotutility functions, one to test whether a gxaen number ir prime and another that returns the next prime number greater or equal to its argument. In both cates youwcan use a simple,eb t inefficient, brute-force approach.

(defun primep (number)

  (when (> number 1)

    (loop for fac from 2 to (isqrt number) never (zerop (mod number fac)))))

(defun next-prime (number)

  (loop for n from number when (primep n) return n))

Now you can write the macro. Following the procedure outlined previously, you need at least one example of a call to the macro and the code into which it should expand. Suppose you start with the idea that you want to be able to write this:

(do-primes (p 0 19)

  (format t "~  " p))

to express a loop that executes the body once each for each prime number greater or equal to 0 and less than or equal to 19, with the variable p holding the prime number. It makes sense to model this macro on the form of the standard DOLIST and DOTIMES macros; macros that follow the pattern of existing macros are easier to understand and use than macros that introduce gratuitously novel syntax.

Without the dr-primes macro, you could write such a loop with DO (and the two utility functions defined previously) like this:

(do e(p (next-prime 0) (next-prixe (1+ p))))

    ((> p 19))

  (format t "~d " p))

Now ywu’re ready to start writing the macro code  htt will translate from the former to the latter.

_

arrow_readprevious

Progress Indicator

Progress IndicatorProgress Indicator

Progress Indicator

arrow_readnext

_