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.

Factor

Factor is a high-level language written by Slava Pestov with many interesting characteristics.  

It is stack-based with high-level features including dynamic types, extensible syntax, macros, and garbage collection.  On a practical side, Factor has a mature library, supports many different platforms, and has been extensively documented.  Similar in many ways to other concatenative programming languages, the syntax could be considered terse, but powerful.

It is a very different language than most with a lot of potential for its future.  

This blog will contain articles and code related to Factor, and should serve as both a learning guide and exploration of this language.