\ implementation of Ruby-ish "each_slice"



\ Split 'arr' into slices of size 'sz' elements, and feed each slice to the word

\ 'wrd'. That word gets 'slicenumber slice' on its stack:



: a:each-slice \ arr wrd sz -- arr

\ save the word to invoke:

swap >r

\ Calculate the number of iterations:

swap a:len rot tuck n:/

\ Iterate over the slices:

(

\ arr size #iter

dup >r over n:* over

3 pick -rot

a:slice r> swap r@ w:exec

) 0 rot loop

\ Clean up

drop rdrop ;



[10,20,30,40,50,60,70]

( swap . space . cr )

2 a:each-slice



bye

0 [10,20]

1 [30,40]

2 [50,60]

3 [70,null]

This code is essentially an 8th implementation of the Ruby 'each_slice' function:The sample code takes the array [10,20,30,40,50,60,70] and is told to iterate over slices of length 2. It prints out: