Книга: Practical Common Lisp

A Sample Macro: do-primes

A Sample Macro: do-primes

To see how this three-step process works, you'll write a macro do-primes that provides a looping construct similar to DOTIMES and DOLIST except that instead of iterating over integers or elements of a list, it iterates over successive prime numbers. This isn't meant to be an example of a particularly useful macro—it's just a vehicle for demonstrating the process.

First, you'll need two utility functions, one to test whether a given number is prime and another that returns the next prime number greater or equal to its argument. In both cases you can use a simple, but 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 "~d " 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 do-primes macro, you could write such a loop with DO (and the two utility functions defined previously) like this:

(do ((p (next-prime 0) (next-prime (1+ p))))
((> p 19))
(format t "~d " p))

Now you're ready to start writing the macro code that will translate from the former to the latter.

Оглавление книги


Генерация: 1.550. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз