0

Let's say I want my method to accept anything that is "number like" i.e. knows how to negate, add, subtract, multiply and divide. It needs to do these with itself and with numbers (Int32 and Float64 for my purposes)

  abstract struct Numberlike
    alias Num = (Int32 | Float64)
    abstract def -
    abstract def +(other : self)
    abstract def +(other : Num)
    abstract def -(other : self)
    abstract def -(other : Num)
    abstract def *(other : self)
    abstract def *(other : Num)
    abstract def /(other : self)
    abstract def /(other : Num)
  end

I'm having a problem where my child struct seems to need to operate on all Numberlike instead of just self. For example

struct Term
  alias Num = (Int32 | Float64)
  getter coeff : Num
  getter sym : Symbol

  def initialize(@coeff, @sym); end

  def -(other : self)
    self.class.new(coeff - other.coeff, sym)
  end
end

The above can return abstract `def Numberlike#-(other : self)` must be implemented by Term because the compiler interprets my requirement as "be sure that all numberlike can operate on all other numberlike" but what I want to find a way to say is "be sure that all terms can operate on numbers and terms (self) as well".

KCE
  • 1,159
  • 8
  • 25
  • 1
    Your code does work as far as I can see: [play](https://play.crystal-lang.org/#/r/6vu0). – Samual May 09 '19 at 20:32
  • @Samual thank you for putting together an isolated example, that's what I should have done in the first place. This pointed out that in my actual code I'm using a `|` to capture both `Num` and `self` and *that* is the source of the problem: [play](https://play.crystal-lang.org/#/r/6vyv). I've asked a [new question](https://stackoverflow.com/questions/56074831/crystal-how-to-implement-multiple-abstract-methods-with-one-method-in-child) since I feel that what you've pointed out is sufficiently different from this one. – KCE May 10 '19 at 09:39

0 Answers0