Reductions

Unlike other Higher Order Functions which lazily returns a transformed sequence, the word
REDUCE
immediately iterates through a sequence. Because
REDUCE
is not lazy you have to ensure that the target sequence is finite otherwise
REDUCE
will never end:
		0 
		1 2 ... 100 take 
			' max reduce .
		100.0 ok
	
The next thing to remember when using
REDUCE
is that it often requires some existing data ("initial values") on the stack. In the example above, the word
MAX
requires two arguments. Without the existing
0
on the stack, the reduction will fail because of
MAX
. Be reminded also that
REDUCE
requires an XT to perform a calculation. The word
.LIST
immediately prints out every element of a sequence and therefore is not lazy. It can be defined using
REDUCE
:
		: .list ['] . reduce cr ;
	
In the example above,
REDUCE
iterates through the sequence and calls
.
to print out each element. You may notice the word
CR
after
REDUCE
ends.
CR
prints a new line and avoids the confusion between the data list and subsequent items printed by other words.

Quiz

Question 1

Write a word
MINIMUM
to find the minimum of a sequence (assume it is finite) without making any assumptions about the upper bound. Hint: you may consider using the first item (what is it called in the sequence?) as the initial upper bound.

Question 2

Write a word
REVERSE
that reverses any list. Does your word work for empty sequences? Hint: when introducing Sequence, do you still remember the difference between two ways of creating a sequence?

Next: Main Menu