[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: Josh Grams
Subject: Re: [gforth] my vsum function is suspiciously non-local
Date: Sun, 7 Mar 2010 15:31:15 -0500
User-agent: Mutt/1.5.18 (2008-05-17)

>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.

: vsum ( addr u -- u2 )
        0 -rot
        cells bounds ?do
                i @ +
        loop ;

Note also that global variables aren't frowned upon in Forth as they are
in other languages.  Certainly you need to be aware of when they are a
problem (and vsum is probably one of these places).

But the general philosophy is that since everything is a word, it's fine
to use a global variable to begin with.  If and when you need something
more sophisticated, replace the variable with a more sophisticated word.
If you never need anything better, you haven't introduced extra anything
into your program.  Remember that Forth originated (and is probably
still mostly used?) in embedded contexts where memory and cpu cycles are
scarce resources.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]