REDUCEtemplate
data
Outputs the result of applying the template to accumulate the items of the data
input, two items at a time.
The template
input must be a two-slot procedure.
Typically, template
is the name of an associative operation, like "SUM.
If the data
input has only one item (member in a list or character in a word), REDUCE outputs that item.
Otherwise, template
is first applied with ?1
filled with the next-to-last item and ?2
with the last item.
Then, if there are more items, the template is applied with ?1
filled with the next item to the left and ?2
with the result from the previous evaluation.
This process continues until all items have been used.
The data
input must not be empty.
It must be either a list or a word (not an array).
If template
is the name of a procedure that is capable of accepting arbitrarily many inputs, it is more efficient to use APPLY instead of REDUCE.
REDUCE is good for associative procedures that have been written to accept exactly two inputs.
TO MAX :a :b
OUTPUT IFELSE :a > :b [:a] [:b]
END
PRINT REDUCE "MAX [2 3 8 7 9 0]
9
Alternatively, REDUCE can be used to write MAX as a procedure that accepts any number of inputs, as SUM does:
TO MAX [:inputs] 2
IF EMPTYP :inputs [(THROW "error [not enough inputs to MAX])]
OUTPUT REDUCE [IFELSE ?1 > ?2 [?1] [?2]] :inputs
END
PRINT (MAX 2 3 8 7 9 0)
9