6.2.2150 ROLL CORE EXT

( xu xu-1 ... x0 u -- xu-1 ... x0 xu )

Remove u. Rotate u+1 items on the top of the stack. An ambiguous condition exists if there are less than u+2 items on the stack before ROLL is executed.

See:

Rationale:

2 ROLL is equivalent to ROT, 1 ROLL is equivalent to SWAP and 0 ROLL is a null operation.

ContributeContributions

ruvavatar of ruv [276] Example implementation for ROLLSuggested reference implementation2023-02-10 21:32:22

: roll ( x0 i*x u.i -- i*x x0 )
  dup 0= if drop exit then  swap >r 1- recurse r> swap
;

JimPetersonavatar of JimPeterson

Very nice, and seems to work well (I'm stealing it!). Would there be any benefit in omitting the 0= and swapping the if/then clauses?... one less operation per iteration? (same with PICK)

ruvavatar of ruv

@JimPeterson, thank you :)

Would there be any benefit in omitting the 0= and swapping the if/then clauses?... one less operation per iteration?

A good optimizing compiler eliminates dup 0= and just generates an appropriate branching instruction.

If we do manual optimizing, then yes, it's probably better:

: roll ( x0 i*x u.i -- i*x x0 )
  dup if swap >r 1- recurse r> swap exit then  drop
;

ruvavatar of ruvNew Version: [276] Example implementation for ROLL

Hide differences

: roll ( x0 ix u.i -- ix x0 )

: roll ( x_u x_u-1 ... x_0 u -- x_u-1 ... x_0 x_u )

dup 0= if drop exit then swap >r 1- recurse r> swap ;


(the stack diagram is copied from the glossary entry)

Reply New Version