["grey","black","green"] var, choices

0 var, index



: next-choice

index @ choices @

over a:@ >r

a:len rot n:1+ swap n:mod

index ! drop r> ;

: alternator \ a -- a[0]

a:shift dup >r

a:push drop r> ;



["grey","black","green"] ' alternator actor: new-color

Let's say you want to select three strings, in order, over and over. Perhaps you want to divide a task among consumers, or you want to use alternating colors in a gui. How might you accomplish that?The way most developers would approach the problem would be to have an array of choices, and an index into the array, something like this:This works, and it will work for any size array. However, it seems inelegant. Here's a more elegant way, using actors:In this case, the actor "new-color" is given a captive data item, the array, which it essentially rotates. It also works for any size array. Both solutions give the same effective result, but the second doesn't require external variables, and the code is shorter (and the inner part of the actor is reusable).