https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/cl...
clamp(x:3, min:1, max:5)
Oh look! No mental strain required to think about what the function does nor what the order should be to minimize mistakes; it’s clear as day!
I wish more languages adopted the option to do this.
clamp({min:2, max:5, x:3})
^parameters can be rearranged as you see fit
There! Now the programmer can decide what’s the way they want to call the function that makes the most sense to them.
Don't get me wrong, I use destructured arguments in js and it works fine, but I thought named arguments in other languages solve that particular issue as well.
Although in this case min/max probably shouldn't have defaults, I think clamp(min, x, max) would be a bit weird in Python?
> This supports any crazy rationale you might have for a particular order, and it is resistant to a lot of bugs you're likely to make since the code isn't particularly repetitive no matter what language you use. Oh and it doesn't have any comparison operators either.
Most of your examples seem to call a "sort" function. Are you sure you're not using any comparisons?
a = sort(x,y,z); return a[1]
or something like this? if(x >= y && x =< z) return x;
if(y >= x && y =< z) return y;
if(z >= x && z =< y) return z;
if(x >= z && x =< y) return x;
if(y >= z && y =< x) return y;
if(z >= y && z =< x) return z;
… return max(low, ( min(val, high) ));
Still hard to avoid comparisons. x.clamp(min, max) Range(min, max).clamp(x)
but this turns to a conversation about syntax, and not about designing API so that we guide our users towards success.
Another way is writing:
which has the advantage of "visually" putting the unknown between two values. That can help people remember which argument goes where.Yet another way is:
That one is popular amongst ML, Haskell, F# etc, programmers because they have partial application. They write something like: and pat themselves on the back because now they have a function for clamping volumes.Another reason this one is popular is because the last expression is likely to be the biggest expression. That might pay dividends on keeping bugs out.
Something I'd like people to consider is simply taking the middle value.
This supports any crazy rationale you might have for a particular order, and it is resistant to a lot of bugs you're likely to make since the code isn't particularly repetitive no matter what language you use. Oh and it doesn't have any comparison operators either.The only real downside is that it's slow.
Oh well.
Before we go and fix the compilers to recognise these contortions as a "clamp" function and optimise for it, maybe it's still worth meditating on next time you have a bunch of conditions in your code.