[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [gforth] my vsum function is suspiciously non-local
From: |
Carsten Strotmann (private) |
Subject: |
Re: [gforth] my vsum function is suspiciously non-local |
Date: |
Sun, 07 Mar 2010 19:20:09 +0100 |
User-agent: |
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-GB; rv:1.9.1.8) Gecko/20100216 Thunderbird/3.0.2 |
-----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 @ ;
>
>
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.14 (Darwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
iEYEARECAAYFAkuT7lkACgkQsUJ3c+pomYFG4ACg48Bqt/EqPOymMou0WpfFjRCz
SEgAoNOrgqzuqLBgcvCy0dCC1FvL7L/X
=pNtG
-----END PGP SIGNATURE-----