4

I'm reading "Practical Common Lisp" and I wonder if Common Lisp supports Duck-Typing like e.g. Ruby?

In Ruby it's possible to call a method on an object regardless of the class as long as it implements a method with the name and argument list that the caller assumes.

What about CLOS? Is it possible to call methods on objects without considering their class simply by assuming that a generic function will cope with it. Perhaps duck-typing is not needed because CLOS doesn't follow a message passing philosophy and methods are not bound to classes.

v_nomad
  • 65
  • 4
  • 1
    As a note, if you need to have a function which always copes (no run-time error of can't find function), you can specialize on `t`, e.g., `(defmethod foo ((incoming-object t)) ...)`. `t` is the top of the type graph. (See 2.15 of CLtL2). – Paul Nathan Feb 17 '12 at 23:09

1 Answers1

15

Perhaps duck-typing is not needed because CLOS doesn't follow a message passing philosophy and methods are not bound to classes.

That is exactly the case. Every generic function can be dynamically specialized for a certain class. There can also be a default implementation. And since Lisp uses dynamic typing, every function can be called with arguments of any type, and for generic functions the dispatch decision, based on the type of argument, is taken at runtime.

Vsevolod Dyomkin
  • 9,343
  • 2
  • 31
  • 36
  • I have to rethink about what a class is. In Common Lisp a class is not defined by a set of methods (which is usually called an interface in Java etc.). Thanks. – v_nomad Feb 18 '12 at 16:39