Is it possible to create a repeat function in Factor Code?

229 views Asked by At

I'm trying to create a function in Factor Code called repeat which expects a non-negative integer n and quotation q following it. It causes q and n to be popped off the stack and then the contents of q executed n times.

So the if the code

[drop] 5 repeat

was executed it would apply drop to the top of the stack 5 times.

I was wondering is it possible to write this in Factor Code or will I have to edit the interpreter and add repeat as a new function that way?

1

There are 1 answers

0
Adeel Zafar Soomro On BEST ANSWER

Using recursion:

: repeat ( quot n -- ) dup 0 > [ over 2dip 1 - repeat ] [ 2drop ] if ; inline

Using a loop:

: repeat ( quot n -- ) [ dup 0 > ] [ over 2dip 1 - ] while 2drop ; inline

Finally, using a pre-defined vocabulary word times:

: repeat ( quot n -- ) swap times ; inline