Function of the day: clamp

It's trivial and useful: clamp restricts a number to a range.

clamp val low high = min (max val low) high

Argument order varies, of course. This particular order has the convenient property that if you forget and write clamp min val max, it still works.

I wanted this function years ago, in an application where I'd written a great many calls to min and max, with a number of mistakes because of the counterintuitive usage (min to impose a maximum, max a minimum). I almost replaced them with clamp, but I couldn't think of a good name for it. Then recently I stumbled across it in some language's standard library (I have already forgotten which) and was delighted to finally be able to put a name to the concept; I must have been (so I ashamedly imagine) the only mathematically inclined programmer in the world who didn't know what it was called.


  1. CLAMP comes up a lot with graphics. Another one that has a name you "just need to know" is LERP aka linear interpolation.

  2. Assuming low <= high, clamp is equivalent to median. And median doesn't care about argument order. Unfortunately verifying that low<=high at runtime makes median require more comparisons. With graphics code often performance sensitive this is not ideal. Also the correspondence is not immediate so the name clamp may be easier to read.

    Here's a language/compiler challenge: automatically optimize calls to median when some comparisons between the arguments can be proven, without the compiler having builtin support for median.


It's OK to comment on old posts.