Where is RBS(trait)-info that can statically typecheck the elements of a Complex

I am makeing a MyNumeric class to use as an element of type Complex.
As we found out in the previous post, the implementation of the unary operator ‘-@’ and the coerce() method was leaked, causing unexpected execution results.

So, isn’t there type definition information like RBS(trait) that enables static type checking of the methods that an object type used as a Complex type element should have?

Elements of Complex don’t have to contain all the methods of the Numeric interface,
so I want to apply a limited constraint to the MyNumeric class, like the “Numeric for Complex trait”.

I would like to hope that the RBS(trait)-info is provided by someone familiar with Complex type requirements.

The code below alone is not sufficient for static type checking.

class MyNumeric < Numeric 
# -----> can be replace  "class MyNumeric <  Numeric_for_Complex_trait"
def "+"()
def "-"()
def "*"()
def inspect()
def to_s()
# missing -@()
# missing coerce(o)
end

p x =Complex.new(MyNumeric.new(xx),MyNumeric.new(yyy))

1 Like

To define the requirements for a class to be used as an element of Complex, you might need a module acting like a Trait where all the required methods get defined. This could give you static type checking, but Ruby is a dynamically typed language and doesn’t provide built-in static type checking.

In your MyNumeric class, you also missed the “initialize” method. As for the missing -@() method, you could implement it where it returns the negated version of itself, and the coerce method returns an array where the first element is an object that has the same class with the second argument, and the second element is the converted value of self.

class MyNumeric < Numeric 
  def initialize(num)
    @num = num
  end
  
  def +(other)
    # implementation here
  end

  def -(other)
    # implementation here
  end 

  def *(other)
    # implementation here
  end 

  def inspect
    # implementation here
  end
  
  def to_s
    # implementation here
  end

  def -@
    # returns the negated version of itself
    -@num
  end
  
  def coerce(other)
    # Returns an array where the first element is 
    # an object that has the same class with the second argument, 
    # and the second element is the converted value of self.
    [other, self.to_f]
  end
end

x =Complex.new(MyNumeric.new(xx),MyNumeric.new(yyy))

However this solution is not quite an equivalent of “Numeric for Complex trait”. You might want to look into Ruby Type Profiler (Steep), or other Ruby static analysis tools for a more detailed static type checking.

Are Ruby 3.0 typeProf and .RBS files( “Numeric for Complex trait”) for Complex not yet available?