by vasilakisfil · 5y ago · 0 comments
I would like Crystal compiler to take into account such definitions and speed up somehow. I know I am talking without experience, I just feel that coming from Ruby to Rust, declaring types on function definitions is not that much of a hassle.
# version 1:
def add(x : Int, y : Int)
x + y
end
# version 2:
def add(x : Number, y : Number)
x + y
end
# version 3:
def add(x : Number, y : String)
x.to_s + y # convert a number to a string with to_s method
end
# version 4:
def add(x, y)
x + y
end
# new methods:
# version 5:
def add(x : Number, y : Bool)
y ? x : 0
end
# version 6:
def add(x : String, y : String)
if x.to_i? && y.to_i?
add x.to_i, y.to_i # calls version 1
else
x + y
end
end
add(2, 3) # => 5
add(1.0, 3.14) # => 4.14
add("Hello ", "Crystal") # => "Hello Crystal"
add(42, " times") # => "42 times"
add 5, true # => 5
add 13, false # => 0
add("12", "13") # => 25
(also from the book)> I just feel that coming from Ruby to Rust, declaring types on function definitions is not that much of a hassle.
I'm another one who doesn't understand why declaring types is seen as a hassle, but then I went from C# to Ruby so perhaps I was already used to it. Happy to bring a little back!