Skip to content

Instantly share code, notes, and snippets.

@Idorobots
Last active December 11, 2015 06:38
Show Gist options
  • Select an option

  • Save Idorobots/4560378 to your computer and use it in GitHub Desktop.

Select an option

Save Idorobots/4560378 to your computer and use it in GitHub Desktop.
ASM MOP example featuring inheritance and multimethod dispatch.
(defclass Point (Object)
'x 'y)
#; A constructor
(defmethod initialize ((p Point) initargs)
(call-next-method)
(initialize-slots p initargs))
#; Point3D inherits the ctor
(defclass Point3D (Point)
'z)
(defvar p1 (new Point 'x 1 'y 2))
(defvar p2 (new Point 'x 2 'y 3))
(defvar p3 (new Point3D 'x 5 'y 5 'z 5))
#; Generic, multiple-dispatch method
(defgeneric distance)
(defmethod distance ((a Point) (b Point))
(write "Point * Point\n")
(distance (new Point3D 'x (a 'x) 'y (a 'y) 'z 0)
(new Point3D 'x (b 'x) 'y (b 'y) 'z 0)))
(defmethod distance ((a Point) (b Point3D))
(write "Point * Point3D\n")
(distance b a))
(defmethod distance ((a Point3D) (b Point))
(write "Point3D * Point\n")
(distance a (new Point3D 'x (b 'x) 'y (b 'y) 'z 0)))
(defmethod distance ((a Point3D) (b Point3D))
(write "Point3D * Point3D\n")
(defvar dx (- (b 'x) (a 'x)))
(defvar dy (- (b 'y) (a 'y)))
(defvar dz (- (b 'z) (a 'z)))
(pow (reduce + (tuple (* dx dx) (* dy dy) (* dz dz)) 0) 0.5))
(distance p1 p2)
(distance p3 p1)
(distance p2 p3)
(distance p3 p3)
#; Prints:
#; Point * Point
#; Point3D * Point3D
#; Point3D * Point
#; Point3D * Point3D
#; Point * Point3D
#; Point3D * Point
#; Point3D * Point3D
#; Point3D * Point3D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment