Skip to content

Instantly share code, notes, and snippets.

@manuel
Created July 21, 2018 06:13
Show Gist options
  • Save manuel/1dc7224fa2321543ceb474e320241536 to your computer and use it in GitHub Desktop.
Save manuel/1dc7224fa2321543ceb474e320241536 to your computer and use it in GitHub Desktop.
;; Define a simple structure
(defstruct point
x
y)
(defun make-point (x y)
(make-instance 'point :x x :y y))
;; Normal Lisp style function
(defun add-points (p1 p2)
(make-point (+ (slot-value p1 'x)
(slot-value p2 'x))
(+ (slot-value p1 'y)
(slot-value p2 '))))
;; With typechecks
(defun add-points ((the point p1) (the point p2))
(make-point (+ (slot-value p1 'x)
(slot-value p2 'x))
(+ (slot-value p1 'y)
(slot-value p2 '))))
;; With typechecks + destructuring, named points
(defun add-points ((the point p1 :x x1 :y y1)
(the point p2 :x x2 :y y2))
(make-point (+ x1 x2) (+ y1 y2)))
;; With typechecks + destructuring, anonymous points
(defun add-points ((the point :x x1 :y y1)
(the point :x x2 :y y2))
(make-point (+ x1 x2) (+ y1 y2)))
;; With destructuring, works for any objects with X and Y slots
(defun add-points ((the :x x1 :y y1)
(the :x x2 :y y2))
(make-point (+ x1 x2) (+ y1 y2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment