I'm playing with Factor trying to get a little understanding of concatenative programming. Writing a word to square a number is trivial:
: square ( n -- n ) dup * ;
But for the life of me I can't seem to figure out how to cube a number:
: cube ( n -- n ) * * ; ! Form a
Doesn't work because the inferred stack effect is ( x x x -- x )
Similarly
: cube ( n -- n ) dup * * ; ! Form b
also fails.
If I were to hard code a cube I would do something like this:
3 3 * 3 *
Which is why my naive guess would be form b.
As I say I'm just playing with Factor and would love to know what I'm missing here--but it's mostly for my curiosity.
There is a builtin word for that:
IN: scratchpad 3 3 ^ .
27
Or if you want to write the word yourself:
: pow ( x n -- y ) 1 - over '[ _ * ] times ;
IN: scratchpad 5 3 pow .
125
You could also formulate cube
using square
:
: cube ( n -- n' ) dup square * ;
IN: scratchpad 6 cube .
216