Trilobite as a Guinea Pig for Simple Macros

278 words | 2016-1-23

Generally speaking, you can write in Lisp and still not be aware of macros. This is a dark art and it’s hard to master, but simple things can be tried.

Making things shorter

The simplest application of macros: reducing the number of lines in the code. Of course, this did not make the object file any less and did not speed up the program. Generally speaking, if macros could treat their arguments not as forms, then it would be possible to generate the left-pattern tables at compile time. I need to think about this.

;; ((left...) (right...)
;;  (up...) (down...)
;;  (left-up...) (right-down...)
;;  (left-down...) (right-up))
(defmacro make-pattern (fn)
     repeat (1- *win-len*)
     for i from 1
     collect ,fn))

(defmacro collect-cells (cond pat)
     repeat (min (1- *win-len*) ,cond)
     for off in ,pat
     collect (+ cell off)))

   ((left-pattern       (make-pattern (- i)))
    (right-pattern      (make-pattern i))
    (up-pattern         (make-pattern (- (* *board-width* i))))
    (down-pattern       (make-pattern (+ (* *board-width* i))))
    (left-up-pattern    (make-pattern (- (* i (1+ *board-width*)))))
    (right-down-pattern (make-pattern (* i (1+ *board-width*))))
    (left-down-pattern  (make-pattern (+ (* i (1- *board-width*)))))
    (right-up-pattern   (make-pattern (- (* i (1- *board-width*))))))
    (defun slow-get-test-patterns (cell)
        ; left
        (collect-cells (mod cell *board-width*) left-pattern)
        ; right
        (collect-cells (- *board-width* (mod cell *board-width*) 1) right-pattern)
        ; up
        (collect-cells (floor cell *board-width*) up-pattern)
        ; down
        (collect-cells (- *board-height* (floor cell *board-width*) 1) down-pattern)
        ; left-up
        (collect-cells (min (mod cell *board-width*) (floor cell *board-width*)) left-up-pattern)
        ; right-down
        (collect-cells (min
                        (- *board-width* (mod cell *board-width*) 1)
                        (- *board-height* (floor cell *board-width*) 1))
        ; left-down
        (collect-cells (min
                        (mod cell *board-width*)
                        (- *board-height* (floor cell *board-width*) 1))
        ; right-up
        (collect-cells (min
                        (- *board-width* (mod cell *board-width*) 1)
                        (floor cell *board-width*))