Crystal how to require implementing class operate on self, instead of all siblings

空扰寡人 提交于 2019-12-25 02:25:22

问题


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".

来源:https://stackoverflow.com/questions/56059132/crystal-how-to-require-implementing-class-operate-on-self-instead-of-all-siblin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!