4 ms·
It gets a bit confusing when the order of arguments is different depending on the library. For instance, with std it's std::clamp(val, min, max), but with Qt it
by f00zz 6y ago
It gets a bit confusing when the order of arguments is different depending on the library. For instance, with std it's std::clamp(val, min, max), but with Qt it's qBound(min, val, max) (for some reason I think the order of arguments in qBound is more logical).
- nemetroid 6y agoIn Haskell, functions often take their arguments in the order that makes the most sense to partially apply. In this case, that would probably be clamp(min, max, val): supplying the first two arguments results in a reusable clamping function.
- ric2b 6y agoIt would be nice if partial application worked with keyword arguments. Actually it would be great if Haskell natively supported keyword arguments.
- Someone 6y agoThe expression Math.min(Math.max(num, min), max) is symmetric in min and num, so it doesn’t matter whether you interchange min and num (or, for that matter, max and num, but that is harder to see from that way to define the ‘clamp’ function)
- f00zz 6y agoGood point, thanks. (Though I've just checked gcc's definition of std::clamp and it looks like __glibcxx_assert(!(__hi < __lo)); return (__val < __lo) ? __lo : (__hi < __val) ? __hi : __val; so order of arguments does matter there.)
- Someone 6y agoSelf reply: Oops. That ‘for that matter’ part isn’t true, as it would mean you could permute the arguments any way you wished.
- wruza 6y agoIt depends. (val, min, max) operates on a first argument, which is more logical as well. (min, max, val) allows range constants to be more visible if <val> is a lenghty expression. In more powerful languages like objective-c this has less sense, as you can always specify all arguments explicitly: [FZUtilityManager clampIntegerValue:(NSInteger)x toRangeWithLowerBound:(NSInteger)min upperBound:(NSInteger)max withError:(out NSError **)error]; Which returns NSIntegerMax and sets the error variable if the range appears to be empty. The chance that max is NSIntegerMax is low, but if your data allows that, you can always put an additional shortcut before clamping. if (min > max) { error = [NSError errorWithDescription:@"min > max occured"]; return NO; // or equivalent } else { x = ... } // use x
- nwallin 6y agoA good text editor solves this problem. I can vouch for emacs, but I would be shocked if there weren't a good way to get vim to do this for you. The list of hard programming things is long; things that are trivially solved by a tool shouldn't be in the list.