3 ms·
Common Lisp to the rescue! (defmethod make-sound ((b bear) (loud-p t))) ;; bear makes loud sound ...) (defmethod make-sound ((b bear) (loud-p n
by kazinator 10y ago
Common Lisp to the rescue!
(defmethod make-sound ((b bear) (loud-p t)))
;; bear makes loud sound
...)
(defmethod make-sound ((b bear) (loud-p null))
;; bear makes quiet sound
...)
If we call (make-sound bear-instance nil), the second method is invoked because loud-p is specialized to the null class, whose only instance is nil. (There is a type nil also, whose domain is the empty set: it has no instance.)
If we call (make-sound bear-instance <any other value>), then the first specialization takes over. It's specialize to T, the grand superclass, so it is a fallback that takes anything. Any value other than nil serves as a Boolean true in Lisp.
It's a magic of Lisp that T stands for "any type" as well as "true". :)
I don't know whether treating Booleans as method parameters like this is good design, but I don't see any immediate down sides.
- rtpg 10y agoAre the semantics to this comparable to Haskell's pattern matching on function arguments?
- icebraining 10y agoAlso known as multiple dispatch, which is supported by many languages: https://en.wikipedia.org/wiki/Multiple_dispatch https://en.wikipedia.org/wiki/Multiple_dispatch