Thursday, October 2, 2008

Clamp

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.

1 comment:

Unknown said...

While the conciseness of your clamp word is really nice, I think the stack effect is unrealistic. You are much more likely to get value a b on the stack.

The definition of clamp would then be:

: clamp ( value a b -- x ) [ max ] [ min ] bi* ;

which is not so terse but as elegant.