Implementing Reduce

This property of being able to treat Words like Literals is very useful because it can considerably simplify programming, especially in processing and analysing data.

To give a simple example, recall the word 
MAX
that puts the maximum of two numbers on the stack. What if we want to determine the maximum of 3 numbers?
 	
		: MAX3 ( n n n -- n ) 
			MAX MAX
		;
		 
		51 46 76 MAX3 . 		
		
will display 76.0, as we expect. What if we want to find the maximum of 6 or 34 numbers? We could use a
DO
loop:
 	
		: MAXN ( m* n -- m ) 
			1 - 0 DO
				MAX 
			LOOP 
		; 
		
		51 46 76 45 67 54 104 0 34  9 MAXN .		
		
will display 104. Note that unlike
MAX3
,
MAXN
needs to be given the number of items of the stack to loop over. Now, supposed we were asked to write a word very similar to
MAXN
, but which finds the minimum of these numbers instead?
 	
		: MINN ( m* n -- m ) 
			1 - 0 DO 
				MIN 
			LOOP 
		; 

		51 46 76 45 67 54 104 0 34  9 MINN .		
		
displays 0, as we expect. Notice that
MAXN
and
MINN
differ in just one way, their use of
MAX
and
MIN
respectively. With this observation and using XTs, we can simplify both
MAXN
and
MINN
. First, define a word call
REDUCE
that captures the looping:
 	
		: REDUCE ( m* n xt -- m ) { f }
			1 - 0 DO 
				f EXECUTE 
			LOOP 
		;

		51 46 76 45 67 54 104 0 34  9 ' MAX REDUCE .		
		
So, in addition to popping some numbers off the stack,
REDUCE
also needs an XT, which it executes within its loop. Next we can easily define both
MAXN
and
MINN
using
REDUCE
:
 	
		: MAXN ['] MAX REDUCE ; 
		: MINN ['] MIN REDUCE ;

		51 46 76 45 67 54 104 0 34  9 MAXN . cr 
		51 46 76 45 67 54 104 0 34  9 MINN . cr 	
		
Note that
[']
works very much like
'
in this context, but it is needed because we are in Compilation Mode. I hope you see that using
REDUCE
we considerably simplified both
MAXN
and
MINN
.

Be sure to try out these examples before moving on!

Quiz

Question 1

In the original definition of 
MAXN
, why was the
1 -
needed?



Question 2


	Could we have written 
REDUCE
without recourse to Local bindings? Explain your answer.



Question 3

Write a word, 
SUMN
that sums the numbers on the stack, with and without using
REDUCE
.



Question 4

Write 
PRODN
that multiplies the numbers on the stack, with and without using
REDUCE
.



Question 5

Considers the word 
CONCAT
that concatenates two pieces of text on the stack, and pushes the result back to the stack. Write
CONCATN
that concatenates text on the stack, with and without using
REDUCE
.



Question 6

What kinds of words can be successfully 
REDUCE
'd? Can you find a pattern?



Question 7

The ability to treat Words like Literals is commonly known as first class functions. 
REDUCE
is a simple example of a Higher Order Function, which takes an XT as an argument. Based on the example above, what would you say are the merits of using Higher Order Functions? And the drawbacks?



Next: Postponing Actions*