您的问题非常广泛,让我们举一个简单的二维形状示例。
下面的代码定义为我们可以这样写:
(isomorphism (alexandria:compose (scale 10)
(lift #'round)
(rotate 90))
(triangle (point 0 0)
(point 1 0)
(point 0 1)))
=> (TRIANGLE (POINT 0 0) (POINT 0 10) (POINT -10 0))
这会计算一个称为同构(保持形状)的简单变换函数,它首先是旋转,然后是计算点的舍入,然后是缩放操作。结果是描述结果形状的列表。复制形状只是与函数#'identity 的同构(但如果使用纯函数方式,它有点没用)。
注意:这里是四舍五入,例如当 cos/sin 给出非常小的浮点数时回落到零;浮点数的使用破坏了形状保持,舍入也是如此,但是当它们组合在一起时,产生的形状是一个实际的同构。根据您的需求目的,这一点正确性/准确性可能重要也可能不重要。您还可以描述应用了哪些转换,并仅“光栅化”它们以进行显示。
变换函数作用于坐标列表,并返回坐标列表:
(defun translate (dx &optional (dy dx))
(lambda (xy) (mapcar #'+ xy (list dx dy))))
(defun scale (sx &optional (sy sx))
(lambda (xy) (mapcar #'* xy (list sx sy))))
(defun rotate (degrees)
(let* ((radians (* degrees pi 1/180))
(cos (cos radians))
(sin (sin radians)))
(lambda (xy)
(destructuring-bind (x y) xy
(list (- (* x cos) (* y sin))
(+ (* y cos) (* x sin)))))))
(defun lift (fn)
(lambda (things)
(mapcar fn things)))
isomorphism 函数定义如下,递归地将形状解构为类型标签(兼作构造函数)和组件,如果是点,则应用变换函数:
(defun isomorphism (transform shape)
(flet ((isomorphism (s) (isomorphism transform s)))
(with-shape (constructor components) shape
(apply constructor
(if (eq constructor 'point)
(funcall transform components)
(mapcar #'isomorphism components))))))
我将shape 和with-shape 定义如下,以便对它们的表示方式进行一些抽象:
(defun shape (constructor components)
(list* constructor components))
(defmacro with-shape ((constructor components) shape &body body)
`(destructuring-bind (,constructor &rest ,components) ,shape
,@body))
我可以用简单的函数定义形状,这些函数可能会或可能不会执行一些检查和规范化:
(defun point (&rest coords)
(shape 'point coords))
(defun triangle (a b c)
(shape 'triangle (list a b c)))
(defun rectangle (x0 y0 x1 y1)
(shape 'rectangle
(list (min x0 x1)
(min y0 y1)
(max x0 x1)
(max y0 y1))))
请注意构造函数总是与函数名称相同的符号。这可以通过宏强制执行,您只需要返回组件列表:
(defconstructor point (x y)
(list x y))
您还可以从上述构造派生构造函数:
(defun rectangle-xywh (x y width height)
(rectangle x y (+ x width) (+ y height)))
上面的形状是根据点来定义的,但是你可以想象有一些形状是由更小的形状组合而成的:
(defun group (&rest shapes)
(shape 'group shapes))
这是一个玩具示例,但作为起点可能会很有用。
然后,如果您想制作一个形状并制作以 90° 为增量旋转的不同副本,您可以这样做:
(loop
for angle from 0 below 360 by 90
collect
(isomorphism (compose (lift #'round)
(rotate angle)
(scale 2)
(translate 10 0))
(group (triangle (point 0 0)
(point 1 0)
(point 0 1)))))