Proposal: add arguments to `int()` to guard value and add default
int() currently takes only one argument, and return nil if the argument is nil
I'm facing a lot of code where I need to guard the value within a range and potentially define a default value.
if (i == nil) i = 0 end
if (i < 0) i = 0 end
if (i > 100) i = 100 end
I'm proposing to have new optional arguments:
int(arg:any, [min: int, max: int, def: int or nil]) -> int or nil
With this the above code would look like:
i = int(i, 0, 100, 0)
It could also used without a default value, hence forcing an int between 0 and 100 or nil
int(-1, 0, 100) # 0
int(1, 0, 100) # 1
int(101, 0, 100) # 100
int(2.5, 0, 100) # 2
int(nil, 0, 100) # nil
@skiars any opinion on this proposal?
Note: code impact would be minimal, and no impact on performace
@skiars any opinion for or against it? If not I will implement it as described above.
I'm a bit confused about the use of min and max, but not default. I suggest naming this argument default instead of def, because def is a keyword.
Gating of numeric ranges is typically done using specialized functions, which helps in maintaining semantic clarity. I would suggest adding these to the math library:
def min(a, b)
return a < b ? a : b
end
def max(a, b)
return a > b ? a : b
end
def bound(lower, value, upper)
return max(lower, min(value, upper))
end
Thanks, using a default value was indeed a bad idea and makes the syntax confusing.
I agree that min/max are missing.
But then the syntax would be:
v = math.bound(0, int(v), 10)
The v = math.bound(0, int(v), 10) is pretty readable. As for the default value of int(), let's take a look at other languages:
parseInt()in JavaScript returnsNaNby default (I don't likeNaN, it can easily break calculations)- In Python, the default constructor of
int()is0, but it may raise an error during parsing