Control flow cookbook
Factor handbook » Factor cookbook

Prev:Shuffle word and definition cookbook
Next:Dynamic variables cookbook


A quotation is an object containing code which can be evaluated.
2 2 + . ! Prints 4 [ 2 2 + . ] ! Pushes a quotation

The quotation pushed by the second example will print 4 when called by call.

Quotations are used to implement control flow. For example, conditional execution is done with if:
: sign-test ( n -- ) dup 0 < [ drop "negative" ] [ zero? [ "zero" ] [ "positive" ] if ] if print ;

The if word takes a boolean, a true quotation, and a false quotation, and executes one of the two quotations depending on the value of the boolean. In Factor, any object not equal to the special value f is considered true, while f is false.

Another useful form of control flow is iteration. You can do something several times:
10 [ "Factor rocks!" print ] times

Now we can look at a new data type, the array:
{ 1 2 3 }

An array differs from a quotation in that it cannot be evaluated; it simply stores data.

You can perform an operation on each element of an array:
USING: io sequences prettyprint ; { 1 2 3 } [ "The number is " write . ] each
The number is 1 The number is 2 The number is 3

You can transform each element, collecting the results in a new array:
{ 5 12 0 -12 -5 } [ sq ] map .
{ 25 144 0 144 25 }

You can create a new array, only containing elements which satisfy some condition:
: negative? ( n -- ? ) 0 < ; { -12 10 16 0 -1 -3 -9 } [ negative? ] filter .
{ -12 -1 -3 -9 }


References
Since quotations are objects, they can be constructed and taken apart at will. You can write code that writes code. Arrays are just one of the various types of sequences, and the sequence operations such as each and map operate on all types of sequences. There are many more sequence iteration operations than the ones above, too.
Combinators
Sequence operations