reduce

reduce reporter-task list

Reduces a list from left to right using the given task, resulting in a single value. This means, for example, that reduce [?1 + ?2] [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.

The first input passed to the task 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 [?2 - ?1] [1 2 3]
=> 2
show reduce [?1] [1 2 3]
=> 1
show reduce [?2] [1 2 3]
=> 3
show reduce sentence [[1 2] [3 [4]] 5]
=> [1 2 3 [4] 5]
show reduce [fput ?2 ?1] (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
    [ifelse-value (length ?1 >= length ?2) [?1] [?2]]
    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
    [ifelse-value (?2 = x) [?1 + 1] [?1]] (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 [(x * ?1) + ?2] coefficients
end

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

Take me to the full NetLogo Dictionary