Skip to content

Instantly share code, notes, and snippets.

@danilomo
Created March 26, 2018 15:30
Show Gist options
  • Save danilomo/fcc5c659f2fcc4f844c2809b4f57b65a to your computer and use it in GitHub Desktop.
Save danilomo/fcc5c659f2fcc4f844c2809b4f57b65a to your computer and use it in GitHub Desktop.
Reverse last n items on the stack
: create-stack
dup
1 + cells allocate throw dup 0 swap !
over over swap cells erase
swap drop
;
: write-on-top ( address n -- address ) swap dup dup @ 1 + cells + rot swap ! ;
: move-cursor ( address n -- address ) over dup @ rot + swap ! ;
: push ( address n -- address )
write-on-top
1 move-cursor
;
: pop ( address -- n address )
dup dup @ cells + @ swap -1 move-cursor ;
: is-empty ( address -- address flag )
dup @ 0= ;
: reverse-stack { i } ( n1 n2 ... ni i -- ni ni-1 ... n2 n1 )
i create-stack
i 0 do
swap push
loop
i create-stack
i 0 do
over pop drop push
loop
swap
free throw
i 0 do
pop
loop
free throw
;
1 2 3 4 5
.s cr
5 reverse-stack
.s cr
5 reverse-stack
.s cr
bye
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment