1
$\begingroup$

Imagine that we have a base class number that has implemented a integer and floats, but not complex numbers and that we would like to extend it to also support complex numbers:

;; this is from the number implementation
(defgeneric add ((a number) (b number))
  (:documentation "Adds two numbers together."))

(defmethod number:add ((a my-complex-number) (b my-complex-number))
  ...)

(defmethod number:add ((a my-complex-number) (b number))
  ...)

(defmethod number:add ((b number) (a my-complex-number))
  ...)

The body of the two last would be exatly the same and yet they are needed in order to do (reduce #'add list-of-numbers) since the number implementation doesn't know how to add complex numbers.

It seems to me like some sort of syntax to indicate the (or some) arguments can occur in any order. In CL I'm sure this can be fixed by making a macro that generates all the versions, but this isn't just a CL problem.

Imagine you have a number tower with an add method in Java and you extend it with a MyComplexNumber class with the same add method. How does noe make sure floatObject.add(complexObject) would work?

ComplexNumber know of the Number class hiarchy but not vice versa. Thus by importing ComplexNumber package it would be nice to "infect" the other classes add methods without changing their code.

Is there a language out there that has abstraction to solve this?

$\endgroup$
  • 1
    $\begingroup$ "Multimethods" could be what you are looking for. $\endgroup$ – Dave Clarke May 24 '15 at 20:58
  • 1
    $\begingroup$ In your specific example, I think you have your class hierarchy upside-down. Making ComplexNumber the base class seems to make all the problems go away. One typically expects subclasses to be more specific and the problem in the example seems to come from the fact that you're trying to make a subclass (complex numbers) that are more general than the base class (real numbers). $\endgroup$ – David Richerby May 24 '15 at 23:33
  • 2
    $\begingroup$ Also, since you're asking for examples of languages with a particular feature, I wonder if Software Engineering would be a better fit for this question? $\endgroup$ – David Richerby May 24 '15 at 23:34
  • 1
    $\begingroup$ @Sylwester OK. Please edit your question to be clear that it's about design: you ask "Is there a language out there that has abstraction to solve this?" so it looks like the answer you want is "Language X can do this." $\endgroup$ – David Richerby May 25 '15 at 7:40
  • 1
    $\begingroup$ I agree with David. That said, parametric types with type bounds can do this for you. $\endgroup$ – Raphael May 25 '15 at 10:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.