-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hello Terence,
my solution would be:
: vsum ( addr u -- n )
CELLS ( addr u ) \ adjust u to size of cell
OVER ( addr u addr )
+ ( addr addr2 )
SWAP ( addr2 addr )
0 ( addr2 addr 0 )
-ROT ( 0 addr2 addr )
DO ( 0 )
I ( 0 i ) \ i = index = address
@ ( 0 u ) \ u = value of cell i
+ ( n ) \ n = result
1 ( n 1 )
CELLS ( n <c> ) \ <c> = size of a cell in byte
\ this is architecture dep.
+LOOP ( n )
; ( n )
condensed:
: vsum ( addr u -- n ) CELLS OVER + SWAP 0 -ROT DO I @ + 1 CELLS +LOOP ;
No local variables needed.
- -- Carsten
On 3/7/10 6:53 PM, Terrence Brannon wrote:
I used a "global variable" named tally to handle this tutorial
assignment, but I think there must be a way to avoid the use of such a
variable in solving this problem. Any help is appreciated:
\ Assignment: Write a definition vsum ( addr u -- n ) that computes
the sum of u cells, with the first of these cells at addr, the next
one at addr cell+ etc.
( Usage:
create vx 2 , 2 , 2 , 2 , 2 ,
vx 5 vsum
)
: loop-range ( number-of-cells -- number-of-cells zero ) 0 ;
: get-value-at-address-offset ( address offset -- v ) cells + @ ;
: increase-value ( n addr -- v+n ) TUCK @ + SWAP ! ;
VARIABLE tally
: vsum { address u }
u loop-range U+DO
address i get-value-at-address-offset
tally increase-value
LOOP
tally @ ;