Thursday, April 26, 2007

Factor Magic, Part 2

In the first part of this article, we looked through some graphics at how you can manipulate the stack with words. We visually examined the positions of the "values" on the stack before and after "shuffle" words were applied.

Copyright (C) 2007 Elie Chaftari

As a reminder take another look at the start position and the other subsequent effects once the rot, -rot, and swap words have been applied.

Another way to express these effects is through "stack notation". With stack notation you describe what parameters a word expects and what that word will leave on the stack once it has been applied.

( n1 n2 n3 -- n )

Here, for example, parameters n1 n2 n3 (in that order) are expected to be on the stack prior to the word's execution. They will be "consumed", leaving a new value n on the stack. A double dash separates input parameters from output parameters.

Let's put this new knowledge to profit to write the above diagram's effects.

rot ( n1 n2 n3 -- n2 n3 n1 ) causes the 3rd stack item to be moved to the top while the 1st and 2nd stack item are pushed down.

-rot
( n1 n2 n3 -- n3 n1 n2 ) causes the top stack item to be moved to the 3rd position while the 2nd and 3rd items are pushed up. A -rot, following a rot, returns the stack to the start position.

swap
( n1 n2 -- n2 n1 ) exchanges the stack positions of the top two stack items.

A good place to discover the remaining shuffle words is in the Factor documentation. Another getting-started spot is the Factor tutorial in the online documentation.

Your "book of magic spells" needs more words of course and this takes some practice.

According to Doug Coleman, one of Factor's top gurus, you need to learn the following words by heart: dup, keep, 2dup, 2keep, swap, pick, rot, -rot, roll, -roll, 2apply, 2array, first2, nth, set-nth, append. He also advises to learn the following words for iterating: each, each-with, map, map-with, 2each, 2map.

Twenty-two words to learn are not a high price for a lot of power. Another nifty trick they'll teach you on the IRC channel is to enter: '\ word see' or '\ word help' in the listener to get immediate insight or help about any word.

( scratchpad ) \ swap see
IN: kernel
PRIMITIVE: swap ( x y -- y x )

Here you "see" the vocabulary (kernel) of the word swap and its stack effect.

If this quick introduction got you interested in more Factor magic, drop by at the IRC channel (irc.freenode.net #concatenative) where you can ask for help and advice. See you there!

No comments: