Basic syntax cookbook
Factor handbook » Factor cookbook

Next:Shuffle word and definition cookbook


The following is a simple snippet of Factor code:
10 sq 5 - .
95

You can click on it to evaluate it in the listener, and it will print the same output value as indicated above.

Factor has a very simple syntax. Your program consists of words and literals. In the above snippet, the words are sq, - and .. The two integers 10 and 5 are literals.

Factor evaluates code left to right, and stores intermediate values on a stack. If you think of the stack as a pile of papers, then pushing a value on the stack corresponds to placing a piece of paper at the top of the pile, while popping a value corresponds to removing the topmost piece.

All words have a stack effect declaration, for example ( x y -- z ) denotes that a word takes two inputs, with y at the top of the stack, and returns one output. Stack effect declarations can be viewed by browsing source code, or using tools such as see; they are also checked by the compiler. See Stack effect declarations.

Coming back to the example in the beginning of this article, the following series of steps occurs as the code is evaluated:
ActionStack contents
10 is pushed on the stack.10
The sq word is executed. It pops one input from the stack (the integer 10) and squares it, pushing the result.100
5 is pushed on the stack.100 5
The - word is executed. It pops two inputs from the stack (the integers 100 and 5) and subtracts 5 from 100, pushing the result.95
The . word is executed. It pops one input from the stack (the integer 95) and prints it in the listener's output area.

Factor supports many other data types:
10.5 "character strings" { 1 2 3 } ! by the way, this is a comment


References
Factor's syntax can be extended, the parser can be called reflectively, and the . word is in fact a general facility for turning almost any object into a form which can be parsed back in again. If this interests you, consult the following sections:
Syntax
The parser
The prettyprinter