gforth
[Top][All Lists]

## Re: [gforth] my vsum function is suspiciously non-local

 From: Elko Tchernev Subject: Re: [gforth] my vsum function is suspiciously non-local Date: Sun, 07 Mar 2010 14:04:31 -0500 User-agent: Thunderbird 2.0.0.23 (Windows/20090812)

A solution without locals is sometimes less readable than desired. This version looks better, I think:
```
: vsum { addr n -- sum }
0                           \ the initial counter
?DO                         \ don't do it if n was 0; negative OK
I @ +                   \ add to the cumulative
1 CELLS +LOOP
;

Carsten Strotmann (private) wrote:
```
```-----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
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

( 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
tally increase-value
LOOP
tally @ ;

```
```

```