Shuffle word and definition cookbook
Factor handbook » Factor cookbook

Prev:Basic syntax cookbook
Next:Control flow cookbook

The dup word makes a copy of the value at the top of the stack:
5 dup * .

The sq word is actually defined as follows:
: sq ( x -- y ) dup * ;

(You could have looked this up yourself by clicking on the sq word itself.)

Note the key elements in a word definition: The colon : denotes the start of a word definition. The name of the new word and a stack effect declaration must immediately follow. The word definition then continues on until the ; token signifies the end of the definition. This type of word definition is called a compound definition.

Factor is all about code reuse through short and logical colon definitions. Breaking up a problem into small pieces which are easy to test is called factoring.

Another example of a colon definition:
: neg ( x -- -x ) 0 swap - ;

Here the swap shuffle word is used to interchange the top two stack elements. Note the difference that swap makes in the following two snippets:
5 0 - ! Computes 5-0 5 0 swap - ! Computes 0-5

Also, in the above example a stack effect declaration is written between ( and ) with a mnemonic description of what the word does to the stack. See Stack effect declarations for details.

For the curious...
This syntax will be familiar to anybody who has used Forth before. However, unlike Forth, some additional static checks are performed. See Definition sanity checking and Stack effect checking.

A whole slew of shuffle words can be used to rearrange the stack. There are forms of word definition other than colon definition, words can be defined entirely at runtime, and word definitions can be annotated with tracing calls and breakpoints without modifying the source code.
Shuffle words
Generic words and methods
Developer tools