On 2025-08-25 02:27, Kyle Katarn wrote:
2025-08-22 at 22:29, Morgan <weedpac...@varteg.nz <mailto:weedpac...@varteg.nz>> wrote:

    On 2025-08-23 05:29, Kyle Katarn wrote:
     >
     > Also from my point of view,  min($max, max($min, $value)) has a
    counter-
     > intuitive reading when used to clamp a value.

    Well, that's trivial to deal with:

    min(max($min, $value), $max));


It's not just about the order of parameters, it's still not intuitive to call max() with $min and min() with $max, you still have to think about what it does step by step to make sense out of it, while clamp($value, min: $min, $max) or clamp(min: $min, value: $value, max: $max) will provide a syntax that immediately make sense for next reader.

Well, clamp(min,value,max) isn't that far from minmax(min,value,max) and then chuck a couple more parentheses in there. Still,

Like the author of the RFC v1 also mentioned, min(max()) is inefficient (see the inner complexity of those functions).
>
Yes, min/max are regarded as array functions, and doesn't special-case the situation where two arguments are passed; no particular reason why that couldn't be done as it seems to be a common use case. Otherwise, the bulk of the complexity comes from type handling and that won't go away in a robust implementation of clamp.


Note that I am not against introducing clamp(). It's certainly not going to hurt to write clamp(min:$min, value:$value, max:$max) instead of min(max($min, $value), $max). I'm going to have to remember to put the parameter names in, because "$min <= $value <= $max" seems by far the most natural ordering (and is how "this value lies between these two extremes" is written in maths).


There is also the use case of returning something other than $min if $value<$min (and other than $max if $value>$max), allowing clamp to filter values that are within the range or too high or too low. That would mean another one or two optional parameters.


For numeric values there's also the closely related rescale() function, which is basically rescale($value, $min, $max) = ($value - $min) / ($max - $min) (it maps the interval [0,1] to [$min,$max] and finds where $value gets carried to by the mapping). Again, a couple more parameters would allow specifying initial intervals other than [0,1].

Reply via email to