Functional Programming Patterns
Reduce Total
Accumulate Values
Reduction combines many values into one result by repeatedly applying a combining function.
Program
Play the script to change the starting value for the accumulation.
reduce_total.R
start <-
values <- c(1, 2, 3)
total <- Reduce(`+`, values, init = start)
label <- paste("total", total, sep = ":")
cat(label, "\n", sep = "")
start <-
values <- c(1, 2, 3)
total <- Reduce(`+`, values, init = start)
label <- paste("total", total, sep = ":")
cat(label, "\n", sep = "")
start <-
values <- c(1, 2, 3)
total <- Reduce(`+`, values, init = start)
label <- paste("total", total, sep = ":")
cat(label, "\n", sep = "")
initial value
`init` gives the reduction a starting accumulator.
combine
`+` combines the accumulator with each value.
reduce
`Reduce` returns one accumulated result.