berry icon indicating copy to clipboard operation
berry copied to clipboard

Proposal: add arguments to `int()` to guard value and add default

Open s-hadinger opened this issue 1 year ago • 4 comments

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

s-hadinger avatar Jun 15 '24 10:06 s-hadinger

@skiars any opinion for or against it? If not I will implement it as described above.

s-hadinger avatar Jun 27 '24 08:06 s-hadinger

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

skiars avatar Jun 28 '24 02:06 skiars

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)

s-hadinger avatar Jun 28 '24 06:06 s-hadinger

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 returns NaN by default (I don't like NaN, it can easily break calculations)
  • In Python, the default constructor of int() is 0, but it may raise an error during parsing

skiars avatar Jun 29 '24 05:06 skiars