Code: Select all
: sum depth 0 swap 0 do + loop ; redefined sum ok
1 2 3 4 sum . 10 ok
Lets assume that 1 2 3 4 are already on the stack.
invoking "sum" executes "depth" first, putting the number "4" on the stack, that is used as limit for the loop.
after that a "0" is put on the stack, defining the index to start with. so the loop should run from 0 to 3 (4 times).
the "do" word takes both upper numbers (4 and 0) from the stack and runs the loop, that should add the remaining numbers on the stack.
That works fine (without the additional "swap 0" if I write
Code: Select all
: sum depth 1 do + loop ; redefined sum ok
1 2 3 4 sum . 10 ok
Testing with:
Code: Select all
: test 3 0 do 1 loop ; redefined test ok
test .s <3> 1 1 1 ok
Can someone help me to understand that?
It is clear that the additional "swap 0" adds another number on the stack (0) that is not affecting the sum, but takes care that the stack is not empty before the loop ends.
But why is in the "sum" definition the loop is running one cycle more then in my "test" definition?
Mario.