reduce1.3

reduce reporter list

Reduces a list from left to right using the given reporter, resulting in a single value. This means, for example, that reduce [ [a b] -> a + b] [1 2 3 4] is equivalent to (((1 + 2) + 3) + 4). If list has a single item, that item is reported. It is an error to reduce an empty list. reporter may be an anonymous reporter or the name of a reporter.

The first input passed to the reporter is the result so far, and the second input is the next item in the list.

Since it can be difficult to develop an intuition about what reduce does, here are some simple examples which, while not useful in themselves, may give you a better understanding of this primitive:

show reduce + [1 2 3]
=> 6
show reduce - [1 2 3]
=> -4
show reduce [ [result-so-far next-item] -> next-item - result-so-far ] [1 2 3]
=> 2
show reduce [ [result-so-far ignored-item] -> result-so-far ] [1 2 3]
=> 1
show reduce [ [ignored next-item] -> next-item ] [1 2 3]
=> 3
show reduce sentence [[1 2] [3 [4]] 5]
=> [1 2 3 [4] 5]
show reduce [ [result-so-far next-item] -> fput next-item result-so-far ] (fput [] [1 2 3 4 5])
=> [5 4 3 2 1]

Here are some more useful examples:

;; find the longest string in a list
to-report longest-string [strings]
  report reduce
    [ [longest-so-far next-string] -> ifelse-value (length longest-so-far >= length next-string) [longest-so-far] [next-string] ]
    strings
end

show longest-string ["hi" "there" "!"]
=> "there"

;; count the number of occurrences of an item in a list
to-report occurrences [x the-list]
  report reduce
    [ [occurrence-count next-item] -> ifelse-value (next-item = x) [occurrence-count + 1] [occurrence-count] ] (fput 0 the-list)
end

show occurrences 1 [1 2 1 3 1 2 3 1 1 4 5 1]
=> 6

;; evaluate the polynomial, with given coefficients, at x
to-report evaluate-polynomial [coefficients x]
  report reduce [ [value coefficient] -> (x * value) + coefficient ] coefficients
end

;; evaluate 3x^2 + 2x + 1 at x = 4
show evaluate-polynomial [3 2 1] 4
=> 57

See also filter, -> (anonymous procedure.

Take me to the full NetLogo Dictionary