home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Power-Programmierung
/
CD1.mdf
/
forth
/
compiler
/
fpc
/
tutor
/
l7p140
< prev
next >
Wrap
Text File
|
1990-07-15
|
3KB
|
74 lines
╔═════════════════════════════════════════════════════╗
║ Lesson 7 Part 140F-PC 3.5 Tutorial by Jack Brown ║
╚═════════════════════════════════════════════════════╝
┌────────────────────────┐
│ The Average Array │
└────────────────────────┘
Here is an application of the compiler extension words CREATE...DOES>
to form an intelligent data structure. The idea is to have an array
that automatically maintains the running average of its non zero
elements in slots 1 through n in array position 0. This means that
every time a number is stored in the array the word itself must be smart
enough to know that the store operation is being performed and then
calculate the average of its non-zero elements and update the value of
the average in position 0 of the array.
Remember that this idea of extending the compiler is new and unheard of
in other languages. How would you do this in C? Of what use would this
type of intelligent array be? Perhaps you could use it in you stock
monitoring program. You could use one of these intelligent arrays to
keep track of the performance of your favorite stocks. As you add each
daily or weekly value of the stock the average would be automatically
calculated. You could even extend this idea to have the array keep
track of more information. How about also maintaining a moving average
of the last three or ??? non zero entries made into the array? Well I
will leave the extensions up to you. Let me know if you find this type
of structure useful or if you come up with any interesting variations.
\ Finds the average of the n elements at adr+4 and stores the
\ result at adr+2. Only non zero elements are counted.
\ AARRAY --> : n : avg : x1 : x2 : ..... : xn :
: AAVERAGE ( adr -- )
DUP 4 + OVER
@ 2*
OVER + SWAP
0 0 2SWAP
?DO I @ DUP 0<>
IF 1 D+ ELSE DROP THEN 2 +LOOP
/ SWAP 2+ ! ;
\ This a flag that indicates access mode.
\ false is fetch mode, the default, and true is store mode.
VARIABLE (:=) (:=) OFF
: := (:=) ON ;
: AARRAY ( n - )
CREATE DUP , 1+ 0
?DO 0 , LOOP
DOES> DUP >R (:=) @ >R (:=) OFF
SWAP 1+ 2* + R>
IF ! R> AAVERAGE
ELSE @ R> DROP
THEN ;
\ Examples of the AARRAY
5 AARRAY junk <enter> ok \ Create an average array with 5 elements.
12 := 2 junk <enter> ok \ Set element number 2 to the value 12
0 junk . <enter> 12 ok \ Fetch element 0, the current average.
8 := 1 junk <enter> ok \ Set element number 1 to 8.
0 junk . <enter> 10 ok \ Now element 0 is 10, the average of 8 and 12.
1 := 4 junk <enter> ok \ Set element number 4 to 1.
0 junk . <enter> 7 ok \ And of course the average is now 7!
\ Now can you think of anything else you might like an intelligent
\ array to do?
┌───────────────────────────────────┐
│ Please Move to Lesson 7 Part 150 │
└───────────────────────────────────┘