Concatenative language/Multiple return values
Stack languages make multiple return values easier to work with than applicative languages. A typical approach in an applicative language is to package the values into a tuple. This works in stack languages too, and is useful if you want to treat the multiple values as a single unit (for example, a 3D point with 3 components); however often it is easier to just push 2 or 3 items on the stack and be done with it.
Most words in Factor still return no values or a single value, but multiple return values are very handy when they come up. A good motivating example is the following. The
at* [ ... handle value ... ] [ ... no value ... ] if
: at ( key assoc -- value ) at* drop ;
This is just the beginning though, and Haskell's pattern matching, or Common Lisp's multiple values support, can easily achieve the same effect with a little more verbosity (you'd have to name the two output values even if you only use them once).
A more interesting case comes up if you have a conditional where each branch outputs two values, which are then consumed by another word:
[ foo ] [ bar ] if +
Perhaps the most unusual application of multiple return values is the concept of "modifiers". Suppose you have a family of words,
do-this do-that do-it frob frob do-this frob do-that frob do-it
But you only defined four words.
Here is a concrete example. Factor has two words for extracting subsequences,
: head ( seq n -- subseq ) (head) subseq ; : tail ( seq n -- subseq ) (tail) subseq ; : head* ( seq n -- subseq ) from-end head ; : tail* ( seq n -- subseq ) from-end tail ; : head-slice ( seq n -- slice ) (head) <slice> ; inline : tail-slice ( seq n -- slice ) (tail) <slice> ; inline : head-slice* ( seq n -- slice ) from-end head-slice ; inline : tail-slice* ( seq n -- slice ) from-end tail-slice ; inline
There is another modifier,
: short ( seq n -- seq n' ) over length min ; inline
So using the above 8 words and
This revision created on Sun, 4 Oct 2009 15:14:42 by DK (frob is as well an operation)
All content is © 2008-2010 by its respective authors. By adding content to this wiki, you agree to release it under the BSD license.