Speaking only to JS is there any reason to write it any other way outside of being clever or as a lambda for singular use? I definitely prefer this version. (Assuming any necessary runtime checks are included for a given project)
There are many reasons to forego readability, especially when writing a library: performance, compatibility, requirements, interpreter/compiler optimizations or even cyclomatic complexity.
In lodash's case it might even be all of the above, although I can't speak for the intentions of the authors since there are no comments to guide readers through the process.
Note GP's link points to what looks like the v3 branch. Check out the latest implementation of clamp, with a few less if statements, and what looks like a NaN check using strict equality if you want your mind blown. https://github.com/lodash/lodash/blob/86a852fe763935bb64c125...
Ah, I see - for clarity I'd rename them FASTEST_POLL_RATE -> SHORTEST_POLL_PERIOD or store them in Hz rather than seconds, so everything was 1/ in that little snippet. Thanks for clearing up my confusion :)
That still leaves the order of Math.min and Math.max undecided and will probably not help much if you get easily confused by the visuals of this code.
I never thought about it but of course there must be code tongue twisters (or more correctly, brain twisters).
Thinking about it, I would probably go with a less confusing implementation. Terse code is hard to read and the compiler is likely clever enough to choose the best implementation anyway.
> and the compiler is likely clever enough to choose the best implementation anyway.
Not in my experience. The compiler is likely to be able to do something decent to it, but it'll probably be different.
Consider the following snippets. For unsigned integers they're all equivalent (and return the max of x and m), but gcc with a wide range of flags can't recognize them as identical.
(x<m) * m + (x>=m) * x
(x<m) * (m-x) + x
x<m ? m : x
I do wonder why it then isn't able to do that for the second line. Possibly because the CPU might have different flags set after processing the substraction?
But I'm not sure if your example is a good argument after I said I prefer less confusing code and you present an example which even confuses the compiler. ;-)
I don't find this a whole lot easier to read to be honest. It seems like doing minification manually, when we have tools to do that for us. An if statement seems a lot clearer, and minifies well https://twitter.com/jaffathecake/status/1296423819238944768
True, nested ternaries can be hard to follow. And the excessive parentheses promote this way of looking at it.
OTOH I think chained ternaries can be simple and easy to understand.
Yes, they are the exact same thing in this case, but getting rid of those nested parens really helps, at least for me.
sarah180's example is a good illustration. I would change the order of the tests because it makes more sense to me to check the min before the max. I'd also make one minor formatting change, because I code in a proportional font and can't line things up in columns:
a < min ? min :
a > max ? max :
a
Maybe people think differently, but to me that is super easy to understand, and much better than the confusing Math.min/max stuff.
I would also wrap the whole thing inside a function:
function clamp( value, min, max ) {
return(
value < min ? min :
value > max ? max :
value
);
}
Now that it's inside a function, you could change the code to use if statements, or Math.min/max, or whatever suits your preferences.
I find myself needing this most frequently in making graphics in R. The scales package has squish() with the same behavior:
squish(25, c(5, 10))
=> 10
squish(6, c(5, 10))
=> 6
squish(1, c(5, 10))
=> 5
If you don't provide the limits it defaults to c(0, 1). That's because this function exists to map to a 0-to-1 range for functions that then map the [0, 1] range to a color ramp.
I'd say the only way this would be better than min/max solution is that you can't accidentally flip it when writing the code - but IMO both suck at expressing intent, clamp reads unambiguously.
Result from sort: 3 in 0.9785124980007822s
Allocated 3000001 object(s)
Result from ternary: 3 in 0.3205206830025418s
Allocated 1 object(s)
Result from clamp: 3 in 0.5030354310001712s
Allocated 2 object(s)
Interestingly the ternary comparison is faster than clamp.
I’ve been programming for living since 2000, but I don’t think that’s relevant. No reason not to use what’s available in standard libraries of whatever language you’re writing.
For example, C++ on AMD64 is very likely to compile std::clamp<double> into 2 instructions, minsd and maxsd. I’m not so sure about nested ternaries mentioned elsewhere in the comments.
Not the person you are replying to, but "a lot of the standard library is horrifying and should never be touched" is pretty standard advice for C++. Mind, I don't think this particular function belongs to that set.
Many performance-critical C++ programmers treat std with suspicion. One thing to keep in mind is that the interface is standard, but the implementations are not, and can foil you on cross-platform development. Another is that you might not need everything that a std container provides, and you can get away with a streamlined data structure that doesn't support those unnecessary operations.
But as a sibling commenter notes... this isn't relevant for min/max.
I'd much rather work on an application that utilized the standard lib than one that brought in dependencies and custom data structures.
If it really is a bottleneck on a hot path then go for it. But not using it because of some ancient anecdotes is going to lead to an unmaintainable mess.
I’m aware some parts of C++ standard library are outright horrible, like iostream and I/O in general. Other parts are questionable, like date & time, locales, and futures.
Meanwhile, other parts of the same standard library are actually OK (most collections, threading, synchronization, atomics, smart pointers, initializer lists). And other parts are awesome, like most of the stuff from <algorithm> header.
Apparently, one of the C++ design goals was to not pay for features which aren’t used. Selectively ignoring stuff from the standard library doesn’t have much downsides.
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).
In 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.
The 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)
It 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:
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
> Modern C# has Math.Clamp() since .NET Core 2.0; too bad it’s not available in desktop edition of the runtime.
Huh, that’s good to know. It’s also in .net standard 2.1. A shame it wasn’t added to Framework 4.8 (which I guess is what you mean by "desktop edition of the runtime"?)
MS .NET framework. Unfortunately, for the last couple years it lags behind .NET core. Even 2 years old .NET core 2.1 is better in some regards than the latest desktop version 4.8.
.NET Framework is now in maintenance mode because they're transitioning to .NET Core (soon called as .NET 5). I would call .NET Framework as Legacy edition rather than Desktop edition
C++17 does have it... but it doesn't compile optimally. It compiles to something based on comparisons instead of the floating-point-specific operations. I tried this on a number of compiler combinations and didn't see anything that would emit min/max instructions for `std::clamp<double>`.
Depends on how the comparisons are ordered. Some of the orderings I've seen in here do respect NaN by virtue of `x > upper_bound` comparing false if either x or upper_bound are NaN.
Wait, really? I just had to double-check my one JS project for bugs and either I used to know this gotcha or I got lucky. My sort()-ing needed to handle NaNs carefully so I was already using custom comparators.
He's saying that, if you have explicitly defined a max and min such that max < min, it is not graceful for the computer to produce a result as though those values were swapped. In other words, garbage in should produce garbage out.
The array implementation sidesteps this by not semantically defining a max and min, instead sorting three arbitrary numbers.
I'm not sure what you mean. The behavior of the max() and min() functions is perfectly well defined. The terms "maximum" and "minimum" are well defined. If I were using those terms I would likely consider the case where max < min to be an error, or have some other meaning, like an empty range.
If I wanted it to automatically flip the values to ensure a sensible range is defined, I would probably use "a" and "b" or "endpoint1" and "endpoint2" or something, because "max" has now become "max or min," which is not the same.
In practice “max” and “min” often aren’t conceptually important for a clamp function. It’s more that you want to keep a value within a range, which is defined by two end points in arbitrary order.
If that is the version of clamp you need, the sort based solution reveals something profound and unexpected: it’s not just the two end points of the range that are equivalent, but all three numbers. Keeping value A between B and C is the same as keeping B between A and C or C between A and B. It’s completely arbitrary which pair you consider to be a range.
I was curious how slow this would be, and here is what JavaScriptCore made of this code:
function clamp(n, min, max) {
return [min, n, max].sort((a, b) => a - b)[1];
}
for (var i = 0; i < 10000000; i++) {
clamp(Math.random() | 0, Math.random() | 0, Math.random() | 0);
}
However, I was pretty disappointed when it seemed to be calling sort each time :( Perhaps I profiled it incorrectly? jsc's profiling data shows that it never hit FTL and nothing ever got inlined. The bytecode for DFG and Baseline is identical:
It's cute but if you used this in an innerloop (like a game, simulation or graphics code where 'clamp' is used often), it'll generate a ton of garbage as well as potential slowdown for no good reason.
This should be completely obvious, but largely irrelevant to the topic at hand. The linked tweet talks about how difficult it is to remember the order of the terms when you implement clamp a certain way; I just wanted to point out that with a different solution, the order surprisingly doesn’t matter at all.
I find that the fact that the functions min and max have the same name as the variables min and max increases cognitive load which makes it harder to think about it.
There was a young coder whose hacks
His manager often claimed lacked
The requisite clarity
For to clamp vars would he:
Math.min(Math.max(number, min), max);
@jaffathecake had a problem of truncation
and posted to Twitter his calculation.
The gist of his attack
was min( max( num, min ), max)
yet refused to add any annotation.
I think your "at most" language is pretty expressive. You could do that as an alias for `min` and `max`
I think `at_most(at_least(num, lower_bound), upper_bound)` is much easier to understand instantly than `min(max(...))`.
I'm tempted to make these aliases myself in some of my development actually. I find a pretty big conceptual difference between "I want to find the minimum point in this data", and "I want to restrict the range of this number" that giving them different names will probably help the readability of my code.
(Of course, for `min(max(...))` I usually write a `clamp()` function to hide that for me, but someones I want to only clamp in one direction)
> (Of course, for `min(max(...))` I usually write a `clamp()` function to hide that for me, but someones I want to only clamp in one direction)
You could make clamp work in only one direction too. clamp(number, None, upper_bound) or the idiomatic equivalent in your language of choice seems pretty readable.
I think the reason it's weird is that we might intuitively think of the "enforce a lower bound" function as taking two named arguments (lowerBound and inputValue) and the order of those two arguments mattering.
But of course, it turns out that the order of the arguments doesn't matter: applying a lowerBound of 5 to an inputValue of 100 turns out to be the exact same thing as applying a lowerBound of 100 to an inputValue of 5.
We know that the order of arguments doesn't matter for the Math.max function, so I think that's where the moment of incredulity comes from.
I use ceil/floor (and make people use whenever I can) if something is going to happen when something hits the ceiling or drops to the floor. And avoid if it is just for clamping.
Next challenge: teach the optimizer to make that almost as fast as the min/max way ;-)
(You can’t reduce it to the min/max call because it also works if you accidentally pass a lower bound that’s larger than the upper bound. Worst-case, the above takes 3 comparisons, unless at least two of the inputs are constants)
It could be trivial to implement an optimisation which does this for that exact code. But what are you going to do? Hand-code an optimisation for every similar thing people could write? I implemented a general solution.
So it also works through metaprogramming:
[1, 2, 3].send(:sort).send(:[], 1)
Through user-defined sorting order:
[1, 2, 3].sort_by { |a, b| b <=> a }[1]
When nested:
[[1, 2].sort[1], 3].sort[0]
And so on.
Note that it also needs to be transparent to debuggers and profilers, it needs to handle multiple method redefinitions (for example what happens if someone redefines the sorting order for integers).
It's not a pattern-matching optimization - it's partial evaluation enabled by a new kind of polymorphic inline cache.
> But what are you going to do? Hand-code an optimisation for every similar thing people could write?
While I appreciate that you solved the general problem, I wonder if there are legs here. Specifically, could one mine GitHub to find automatically common patterns that one could write specific optimizers for, or at minimum, leverage that to learn what semi-general cases are worth optimizing? To my knowledge optimizing compilers already do have effectively handlers for common operations, but I don’t know if anyone has leveraged “big data” to help guide this.
IIRC, various tweaks and optimizations in Java were guided by Sun analyzing their own code based. GitHub is just so much bigger, and polyglot.
I'm glad things like this are being worked on. I have been writing a set of implementations of the nBody benchmark in JavaScript using various forms of abstractions. In an ideal world they should all take the same speed since they perform the same fundamental task and produce the same result. They just represent different scales of optimization effort.
It's interesting seeing the difference between vectors in arrays vs objects and if you do immutable versions. The trickiest to optimize form is using a micro vector library which uses closures and array map().
var vop = op => ((a, b) => (a.map((v, i) => op(v, b[i]))));
var vdiff = vop((a, b) => a - b);
var vequals = (a, b) => { return (vdiff(a, b).reduce((c, d) => c + Math.abs(d), 0)) === 0;};
var vadd = vop((a, b) => a + b);
var vdot = (a, b) => a.reduce((ac, av, i) => ac += av * b[i], 0);
var vlength = a => Math.sqrt(vdot(a, a));
var vscale = (a, b) => a.map(v => v * b);
var vdistance = (a, b) => vlength(vdiff(a, b));
Currently on my lowly atom laptop and FireFox. The version using mutable objects is ten times faster than the mapping immutable array version. I live in hope that one day there will be an optimizer that turns
Does NaN have an "order" in the set of reals or integers or whatever? I would have no idea what to expect from `min(NaN, x)` or max same. But is it specified by an IEEE standard or something?
Both min and max should return NaN, if any of their parameters is NaN. Sorting can be defined where to place the NaNs (head/tail) but it's largely irrelevant in this case as simply the substitution won't be permitted by any compiler.
NaN is part of IEEE754 but of course it's not a 'real' number (integer numbers don't have NaNs)
Edit: you can consider NaN (and to a degree both infinities) as an exception, once it occurs - it has to be propagated. Any operation involving NaN should be returning NaN, any operation comparing NaN to anything has to return 'false'. That includes "if (NaN == NaN)". boolean isNaN(double d) is effectively "return d != d;"
The reference to IEEE 754 is made later on, mostly to answer the question posted. I meant regular functions in C alike languages - Math.min/max - java/javascript, fmin/fmax - C++. They do the "right" thing to propagate the NaN
No, it breaks the ordering requirements. NaN compares greater than and less than every number.
You can say that a call to max should return NaN if any argument is NaN, but you can't say the same about sorting. (For one thing... sorting an array doesn't return a scalar value.) Sorting is done with comparisons, and what happens if a NaN gets into the list of values will depend on which specific comparisons happen to be done.
Yes, but in that context, ∞ is a number. We often interpret "NaN" to mean "infinity," but it only means "not a number." Maybe I'm being pedantic, but if we want a token representing infinity as a number, it ought not be called "not a number."
IEEE754 has both infinity and NaN. They are different. NaN is always the result of an invalid operation, such as trying to take the square root of a negative number. Infinity is for when the result would be valid, but is too large in magnitude to represent. There is both positive and negative infinity.
The only reason I know what to expect is because Suckerpinch on YouTube made a video in which he managed to define a logic system using NaN and +∞, and does so by abusing min and max, among other expressions:
The functions
minNum and maxNum ([IEEE 754-2008, 5.3.1, p19]) take two
arguments and return the min and max, respectively. They
have the special, distinguished property that “if exactly one
argument is NaN, they return the other. If both are NaN they
return NaN.”
Edit: As of 2019, the formerly required minNum, maxNum, minNumMag, and maxNumMag in IEEE 754-2008 are now deleted due to their non-associativity. [https://en.wikipedia.org/wiki/IEEE_754#2019]
Having a NaN at that point feels like a bug anyway, the solution is probably to check the arguments and throw an exception if NaN is provided (or use an input type that doesn't allow invalid values)
That would depend on what you do with the NaNs. For instance I have been using them extensively in time series data representation to denote a specific entry has no value - think of Saturday and stock/forex markets.
Null does not pertain to primitive types in java and in C - it'd be zero when applied to a 'double'. (note: you want double[] as backing storage in java and you absolutely do not indirections). Aside that I have quite a good idea how NaN is represented internally and what it does, e.g. you can have several different NaNs that have different representation bitwise. Baring that - NaNs are pretty decent to represent lack of value as all operations with them result into a NaN. In the end NaN is just a composition of bits that the hardware can optimize for.
You know what's great about that? The order of the arguments doesn't matter. So all the debate about "should it be num, min, max or min, num, max"- your solution does not care. Put them in any order you like!
You've redefined the problem from clamping a given value into picking the middle value from 3. This is a lovely way to re-interpret it.
Well, the order of the arguments does matter. Sorting three values requires 2.67 comparisons where clamping a value between two other values requires exactly 2. There are plenty of contexts where cleverly avoiding a problem by doing 33% more work isn't viewed as desirable.
True, but I think there are more situations where minimizing the chance of programmer error, now or in the future, is more important than a micro-optimization that will never matter. All depends on context.
An Elixir convention I've seen is to put the thing you're operating on first, so that you can compose functions using the `|>` operator, which places the previous expression as the first argument of the function to the right.
Maybe something like this?
defmodule Compare do
def clamp(number, minimum, maximum) do
number
|> max(minimum)
|> min(maximum)
end
end
import Compare
clamp(5, 1, 10) # 5
clamp(1, 5, 10) # 5
clamp(10, 1, 5) # 5
some_number
|> clamp(min, max)
As a side note, I think the Elixir |> operator is a stroke of genius that other languages should take a look at. Making the pipe operator append the _first_ argument has the following benefits
1.) It makes the most "important" argument of the function the first thing you read in function signatures
2.) If you need to add more arguments to a function signature later, they tend to be less important the original args, so they tend to make sense at the end
3.) It creates a convention for all libraries to follow so they can leverage the pipe operator. Its really jarring when the thing you want to put in a pipeline isn't the first argument (looking at you `Regex`[0] which puts the regular expression as the first arg and not the string)
> It makes the most "important" argument of the function the first thing you read in function signatures
Doesn't that make writing functions that can use partial application harder? e.g. If I was writing clamp i would want the signature to be
(defn clamp [min max n] ,,,)
Then I can do:
(map (partial clamp 1 11) [-14 2 5 8 11 15 18])
I know when I use Clojures threading macros I use thread last way more than any of the others. My next most common would be piping it into arbitrary locations, e.g.:
; pipe into an arbitrary spot (specified here as o)
(as-> (range 1 10) o
(map inc o)
(filter even? o)
(reduce + o))
defmodule Math do
def clamp(num, _min, max) when num > max, do: max
def clamp(num, min, _max) when num < min, do: min
def clamp(num, _min, _max), do: num
end
Following xxs example of looking at NaN behavior, with this code, a bound (say lower) of NaN means that bound is disabled. Which may or may not be what you want.
Do people actually have trouble with this repeatedly, or just when they first learn about it? I started using this implementation of clamp a few years ago, and while it gave me some trouble when I first implemented it, the pattern is very simple, and I got used to it very quickly.
I use Common Lisp:
> (max min (min max n))
Is the difference my choice of language, my personal mental hardware, the amount of familiarity one has with the pattern, or none of the above?
func helper(a float64, c chan float64){
time.Sleep(time.Duration(a) * time.Second)
c <- a
}
func clamp(a float64, min float64, max float64) float64 {
c := make(chan float64, 3)
go helper(a, c)
go helper(min, c)
go helper(max, c)
_, out, _ := <-c, <-c, <-c
return out
}
Fun seeing that pretty much everyone else finds that idiom confusing too. Half-serious, over breakfast:
(case [(> n min) (< n max)]
[true true] n
[true false] max
[false true] min)
(Side note: Clojure's `>` and `<` are kind of unreadable to begin with. Turning `if (> n min)` into "if n is greater than min" takes some work for me, still, after more than a year.)
no idea what's going on there, I know some of those variables are actually functions but the whole thing is unreadable unless you have experience in haskell imo
This is the TXR Lisp interactive listener of TXR 242.
Quit with :quit or Ctrl-D on an empty line. Ctrl-X ? for cheatsheet.
1> (clamp 1 10 -1)
1
2> (clamp 1 10 15)
10
3> (clamp 1 10 5)
5
Added on August 13, 2015 by commit f2e197dcd31d737bf23816107343f67e2bf6dd8e
For casual readers,
`dip` pops the top of the stack, executes a quotation, then pushes the top of the stack back on.
So this pops the max value off the stack, applies the quoted `max` word to the x and min stack values, then pops the max value back on the stack and applies the `min` word to the result and the max.
290 comments
[ 0.21 ms ] story [ 816 ms ] threadThat doesn't seem unreasonable. (In fact, that's what happens with the min/max approach).
In lodash's case it might even be all of the above, although I can't speak for the intentions of the authors since there are no comments to guide readers through the process.
Note GP's link points to what looks like the v3 branch. Check out the latest implementation of clamp, with a few less if statements, and what looks like a NaN check using strict equality if you want your mind blown. https://github.com/lodash/lodash/blob/86a852fe763935bb64c125...
clamp(null) returns 0
clamp(undefined) returns NaN
clamp(1, NaN, NaN) returns 0
clamp(1) returns 0
clamp(1, 5, NaN) returns 5
JavaScript is hard to write safe code for.
It would take them less time to convince themself if they switched min and num to put the values in proper semantic order: min < num < max.
Math.min(Math.max(min, num), max)
I never thought about it but of course there must be code tongue twisters (or more correctly, brain twisters).
Thinking about it, I would probably go with a less confusing implementation. Terse code is hard to read and the compiler is likely clever enough to choose the best implementation anyway.
Not in my experience. The compiler is likely to be able to do something decent to it, but it'll probably be different.
Consider the following snippets. For unsigned integers they're all equivalent (and return the max of x and m), but gcc with a wide range of flags can't recognize them as identical.
Interestingly in your example, clang is able to resolve the first and the third line to the same assembler code.
https://godbolt.org/z/navMEc
I do wonder why it then isn't able to do that for the second line. Possibly because the CPU might have different flags set after processing the substraction?
But I'm not sure if your example is a good argument after I said I prefer less confusing code and you present an example which even confuses the compiler. ;-)
But it looks dead: https://github.com/rwaldron/proposal-math-extensions/issues/...
As someone mentioned in the thread, nested ternary is easier to interpret:
(a > max ? max : (a < min ? min : a))
OTOH I think chained ternaries can be simple and easy to understand.
Yes, they are the exact same thing in this case, but getting rid of those nested parens really helps, at least for me.
sarah180's example is a good illustration. I would change the order of the tests because it makes more sense to me to check the min before the max. I'd also make one minor formatting change, because I code in a proportional font and can't line things up in columns:
Maybe people think differently, but to me that is super easy to understand, and much better than the confusing Math.min/max stuff.I would also wrap the whole thing inside a function:
Now that it's inside a function, you could change the code to use if statements, or Math.min/max, or whatever suits your preferences.squish(25, c(5, 10)) => 10
squish(6, c(5, 10)) => 6
squish(1, c(5, 10)) => 5
If you don't provide the limits it defaults to c(0, 1). That's because this function exists to map to a 0-to-1 range for functions that then map the [0, 1] range to a color ramp.
https://repl.it/repls/GargantuanThistleLink
Interestingly the ternary comparison is faster than clamp.C++/17 has std::clamp() in <algorithm> header.
Modern C# has Math.Clamp() since .NET Core 2.0; too bad it’s not available in desktop edition of the runtime.
HLSL has clamp() intrinsic function, and a special version saturate() to clamp into [ 0 .. +1 ] interval.
For example, C++ on AMD64 is very likely to compile std::clamp<double> into 2 instructions, minsd and maxsd. I’m not so sure about nested ternaries mentioned elsewhere in the comments.
And if you don't already know that in your soul, I will appear to be a genuine crackpot, and the reasons not to use std::* will still exist.
But as a sibling commenter notes... this isn't relevant for min/max.
If it really is a bottleneck on a hot path then go for it. But not using it because of some ancient anecdotes is going to lead to an unmaintainable mess.
I’m aware some parts of C++ standard library are outright horrible, like iostream and I/O in general. Other parts are questionable, like date & time, locales, and futures.
Meanwhile, other parts of the same standard library are actually OK (most collections, threading, synchronization, atomics, smart pointers, initializer lists). And other parts are awesome, like most of the stuff from <algorithm> header.
Apparently, one of the C++ design goals was to not pay for features which aren’t used. Selectively ignoring stuff from the standard library doesn’t have much downsides.
It's actually the std::min/std::max version that goes to minsd/maxsd in both clang/gcc.
> Fout bij het maken van de databaseconnectie
(Though I've just checked gcc's definition of std::clamp and it looks like
so order of arguments does matter there.)The list of hard programming things is long; things that are trivially solved by a tool shouldn't be in the list.
Huh, that’s good to know. It’s also in .net standard 2.1. A shame it wasn’t added to Framework 4.8 (which I guess is what you mean by "desktop edition of the runtime"?)
huh?
https://www.godbolt.org/z/MKqTvE
https://stackoverflow.com/questions/21019902/why-cant-javasc...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
[ROT 13] spoiler: cnefrVag frpbaq nethzrag vf onfr, znc frpbaq nethzrag vf vaqrk va neenl. 10 vf gur frpbaq nethzrag, vaqrk 1. cnefrVag(10, 1) unf vyyrtny onfr
[0] https://rot13.com/
Only by defining a `const subtract = (a, b) => a - b;`, which isn't really point-free.
Or by using a different language.
I really love this! I’m not sure whether to laugh, cry, or applaud, but I love how it makes me feel all those emotions at the same time.
The array implementation sidesteps this by not semantically defining a max and min, instead sorting three arbitrary numbers.
If I wanted it to automatically flip the values to ensure a sensible range is defined, I would probably use "a" and "b" or "endpoint1" and "endpoint2" or something, because "max" has now become "max or min," which is not the same.
If that is the version of clamp you need, the sort based solution reveals something profound and unexpected: it’s not just the two end points of the range that are equivalent, but all three numbers. Keeping value A between B and C is the same as keeping B between A and C or C between A and B. It’s completely arbitrary which pair you consider to be a range.
(Shots fired)
I still found your approach interesting and it's rare there's a perfect approach so don't take it to heart.
I find the following easier to read :
near get(), post(), and ajax()
// we alias at import
// to keep all the code short
min(max(number, min), max)
But "min(-, constant_x)" should be thought of as "at most constant_x" and similarly for max. Maybe there's a way to make it more expressive.
I think `at_most(at_least(num, lower_bound), upper_bound)` is much easier to understand instantly than `min(max(...))`.
I'm tempted to make these aliases myself in some of my development actually. I find a pretty big conceptual difference between "I want to find the minimum point in this data", and "I want to restrict the range of this number" that giving them different names will probably help the readability of my code.
(Of course, for `min(max(...))` I usually write a `clamp()` function to hide that for me, but someones I want to only clamp in one direction)
You could make clamp work in only one direction too. clamp(number, None, upper_bound) or the idiomatic equivalent in your language of choice seems pretty readable.
I sometimes mix up "min" as "take the minimum" rather than "take the larger given this minimum".
But of course, it turns out that the order of the arguments doesn't matter: applying a lowerBound of 5 to an inputValue of 100 turns out to be the exact same thing as applying a lowerBound of 100 to an inputValue of 5.
We know that the order of arguments doesn't matter for the Math.max function, so I think that's where the moment of incredulity comes from.
(You can’t reduce it to the min/max call because it also works if you accidentally pass a lower bound that’s larger than the upper bound. Worst-case, the above takes 3 comparisons, unless at least two of the inputs are constants)
I did exactly this for my PhD!
https://chrisseaton.com/phd/
It could be trivial to implement an optimisation which does this for that exact code. But what are you going to do? Hand-code an optimisation for every similar thing people could write? I implemented a general solution.
So it also works through metaprogramming:
Through user-defined sorting order: When nested: And so on.Note that it also needs to be transparent to debuggers and profilers, it needs to handle multiple method redefinitions (for example what happens if someone redefines the sorting order for integers).
It's not a pattern-matching optimization - it's partial evaluation enabled by a new kind of polymorphic inline cache.
While I appreciate that you solved the general problem, I wonder if there are legs here. Specifically, could one mine GitHub to find automatically common patterns that one could write specific optimizers for, or at minimum, leverage that to learn what semi-general cases are worth optimizing? To my knowledge optimizing compilers already do have effectively handlers for common operations, but I don’t know if anyone has leveraged “big data” to help guide this.
IIRC, various tweaks and optimizations in Java were guided by Sun analyzing their own code based. GitHub is just so much bigger, and polyglot.
It's interesting seeing the difference between vectors in arrays vs objects and if you do immutable versions. The trickiest to optimize form is using a micro vector library which uses closures and array map().
Currently on my lowly atom laptop and FireFox. The version using mutable objects is ten times faster than the mapping immutable array version. I live in hope that one day there will be an optimizer that turns Into a CPU optimum (or dare I suggest GPU) version of a matrix multiply.NaN is part of IEEE754 but of course it's not a 'real' number (integer numbers don't have NaNs)
Edit: you can consider NaN (and to a degree both infinities) as an exception, once it occurs - it has to be propagated. Any operation involving NaN should be returning NaN, any operation comparing NaN to anything has to return 'false'. That includes "if (NaN == NaN)". boolean isNaN(double d) is effectively "return d != d;"
That's not a given, though. IEEE 754-2008 defined min and max as returning the non-NaN parameter. They have been removed in IEEE 754-2019 though.
You can say that a call to max should return NaN if any argument is NaN, but you can't say the same about sorting. (For one thing... sorting an array doesn't return a scalar value.) Sorting is done with comparisons, and what happens if a NaN gets into the list of values will depend on which specific comparisons happen to be done.
By definition, something that is not a number (real, integer, etc.) cannot be compared to something that is a number.
https://youtu.be/5TFDG-y-EHs
Source: http://tom7.org/nand/nand.pdf
Edit: As of 2019, the formerly required minNum, maxNum, minNumMag, and maxNumMag in IEEE 754-2008 are now deleted due to their non-associativity. [https://en.wikipedia.org/wiki/IEEE_754#2019]
Recording the lack of a value is what null is for.
You've redefined the problem from clamping a given value into picking the middle value from 3. This is a lovely way to re-interpret it.
BRB, just checking some code…
Math.max(lower_bound, Math.min(num, upper_bound))
Since i read right to left.
Maybe something like this?
As a side note, I think the Elixir |> operator is a stroke of genius that other languages should take a look at. Making the pipe operator append the _first_ argument has the following benefits1.) It makes the most "important" argument of the function the first thing you read in function signatures
2.) If you need to add more arguments to a function signature later, they tend to be less important the original args, so they tend to make sense at the end
3.) It creates a convention for all libraries to follow so they can leverage the pipe operator. Its really jarring when the thing you want to put in a pipeline isn't the first argument (looking at you `Regex`[0] which puts the regular expression as the first arg and not the string)
[0] https://hexdocs.pm/elixir/Regex.html#replace/4
Doesn't that make writing functions that can use partial application harder? e.g. If I was writing clamp i would want the signature to be
Then I can do: I know when I use Clojures threading macros I use thread last way more than any of the others. My next most common would be piping it into arbitrary locations, e.g.: I rarely use thread-first.I've never felt pain around partial application because I use the anonymous function short hand a good deal
I use Common Lisp:
> (max min (min max n))
Is the difference my choice of language, my personal mental hardware, the amount of familiarity one has with the pattern, or none of the above?
If a < min, then the sorted array is [a, min, max]. The median is min, which is a clamped to min.
If a > max, then the sorted array is [min, max, a]. The median is max, which is a clamped to max.
if num > max: num = max
if num < min: num = min
I felt the same for awhile but now I just mentally put the operator between the operands, so (> 3 2) is the same as 3 > 2.
So
isI really think we deserve more syntax that allowed something like this, because otherwise one needs to read `(bar (foo a b) c)` inside-out.
I never thought of it that way, but it is true that it can be used as a pipe.
Fundamentally it's just the dual of (): Haskell lets you use operators as infix functions by wrapping them in () so
is the same as and conversely lets you use prefix (binary) functions as operators by wrapping them in backticks.You can even combine those through sections, which serve to partially apply infix operators: https://wiki.haskell.org/Section_of_an_infix_operator
In pure Python `statistics.median([min, max, num])` also works.
So this pops the max value off the stack, applies the quoted `max` word to the x and min stack values, then pops the max value back on the stack and applies the `min` word to the result and the max.