The Flow of Factor

This is an interactive tutorial about Factor the programming language. See also visually-oriented Factor playground.

Feedback: henrik.huttunen@gmail.com

You must enable browser scripting to see interpreted results!

Brief introduction to Factor

Factor is a language for practical use. It has powerful features such as closures and macros but it differs from other mainstream languages in more profound way. Mainly the programming is oriented not on data but on functions, which are called words. In Factor this approach comes from that mostly you don't pass parameters to functions explicitly. The values you operate upon are on an implicit stack. Also, the model of executing functions is straightforward: they are interpreted from left to right.

In combination with parse time manipulation (parse words), this approach gives unique feel towards problem solving. For example, to refactor long function into subfunctions, you just cut-and-paste any sequence of words into new functions. Also understanding the flow of programs is greatly simplified. This means that libraries that are specifically suited for certain domains, are beautifully expressed but also comprehensible semantically [1].

[1] Contrast this f.ex. to Scala, in which implicits are cumbersome and understanding expressions containing them takes effort for a novice.

Your first words

This tutorial is interactive, so that you can concretely get a feel for how stack oriented approach works. Luckily for us, stack is easily visualizable. Here's our first example.

In below you see a stack under "before" and "after" titles. In the between is the word (i.e. function) that is executed. The word starts operating on the stack on the left; the stack after execution is on the right-hand side.

Our first word is swap, which is a basic shuffle word. It changes the stack by switching the places of two topmost values. See how values 1 and 2 appear on different slots of the stacks but 3 is not affected.

  • 1
  • 2
  • 3
swap

Here's another one. dup duplicates the topmost value.

  • 4
dup

We can combine two words together by concatenating them into space-separated string. Remember that the execution goes from left to right. So here's swap dup.

  • 4
  • 1
swap dup

It's your turn to shuffle the stack. Write a combination of swap and dup into the input box and press enter or click the execute button. You can also add more values onto stack by just separating them with spaces, e.g. 5 3.

  • 1
  • 2

This was only the beginning. I'm going to cover most basic use cases of Factor later. Stay tuned.