Clamp
Thursday, October 2, 2008
One occasionally useful snippet of code when working with numbers is the clamp function for restricting a number to a range of values (either the minimum, maximum, or somewhere in-between).
In a language like Python or C or Java, one might write this function:
def clamp(a, value, b):
return max(a, min(b, value))
In Factor, this is written in a similar, but more terse, manner:
: clamp ( a value b -- x )
min max ;
Since the arguments are located on the stack, the “min” word operates on “value” and “b”, placing the “result” on the stack, then the “max” word operates on “a” and “result”, placing the final result on the stack.
Simple. Elegant.