Skip to content

Instantly share code, notes, and snippets.

@epanji
Last active February 10, 2018 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epanji/c93fea8ed9f7adaafb0a782f877dcc1b to your computer and use it in GitHub Desktop.
Save epanji/c93fea8ed9f7adaafb0a782f877dcc1b to your computer and use it in GitHub Desktop.
Experiment metaclass funcallable-standard-class.
(defpackage #:experiment
(:use :cl :sb-mop))
(in-package #:experiment)
;; ------------------------------------------------------------------------------------------------
(defclass area ()
((width :initarg :w)
(height :initarg :h))
(:default-initargs :w 0 :h 0)
(:metaclass funcallable-standard-class))
(defmethod initialize-instance :after ((instance area) &key)
(with-slots (width height) instance
(set-funcallable-instance-function
instance #'(lambda () (* width height)))))
;; ------------------------------------------------------------------------------------------------
(defmethod calculate ((instance area))
(with-slots (width height) instance
(* width height)))
;; ------------------------------------------------------------------------------------------------
(defun test ()
(let ((area (make-instance 'area :w 4 :h 3)))
(format t "(eql 12 (funcall area)) => ~a~%"
(eql 12 (funcall area)))
(format t "(eql 12 (calculate area)) => ~a~%"
(eql 12 (calculate area)))))
;; (eql 12 (funcall area)) => T
;; (eql 12 (calculate area)) => T
(defun test2 ()
(let ((instances (list (make-instance 'area :w 4 :h 3)
(make-instance 'area :w 3 :h 2)
(make-instance 'area :w 2 :h 1))))
(format t "(equal (mapcar #'funcall instances) (mapcar #'calculate instances)) => ~a~%"
(equal (mapcar #'funcall instances)
(mapcar #'calculate instances)))))
;; (equal (mapcar #'funcall instances) (mapcar #'calculate instances)) => T
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment