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
Replay: real traced execution (multi-file project)
start <- 0
values <- c(1, 2, 3)
total <- Reduce(`+`, values, init = start)
label <- paste("total", total, sep = ":")
cat(label, "\n", sep = "")
start <- 10
values <- c(1, 2, 3)
total <- Reduce(`+`, values, init = start)
label <- paste("total", total, sep = ":")
cat(label, "\n", sep = "")
start <- 20
values <- c(1, 2, 3)
total <- Reduce(`+`, values, init = start)
label <- paste("total", total, sep = ":")
cat(label, "\n", sep = "")
start ← 0
1start <- 02values <- c(1, 2, 3)values this step0startvalues ← 1, 2, 3
1start <- 02values <- c(1, 2, 3)3total <- Reduce(`+`, values, init = start)values this step1, 2, 3valuestotal ← 6
2values <- c(1, 2, 3)3total <- Reduce(`+`, values, init = start)4label <- paste("total", total, sep = ":")values this step6total0start1, 2, 3valueslabel ← total:6
3total <- Reduce(`+`, values, init = start)4label <- paste("total", total, sep = ":")5cat(label, "\n", sep = "")values this steptotal:6label6totalcat(label, " ", sep = "")
4label <- paste("total", total, sep = ":")5cat(label, "\n", sep = "")outputtotal:6values this steptotal:6label
start ← 10
1start <- 102values <- c(1, 2, 3)values this step10startvalues ← 1, 2, 3
1start <- 102values <- c(1, 2, 3)3total <- Reduce(`+`, values, init = start)values this step1, 2, 3valuestotal ← 16
2values <- c(1, 2, 3)3total <- Reduce(`+`, values, init = start)4label <- paste("total", total, sep = ":")values this step16total10start1, 2, 3valueslabel ← total:16
3total <- Reduce(`+`, values, init = start)4label <- paste("total", total, sep = ":")5cat(label, "\n", sep = "")values this steptotal:16label16totalcat(label, " ", sep = "")
4label <- paste("total", total, sep = ":")5cat(label, "\n", sep = "")outputtotal:16values this steptotal:16label
start ← 20
1start <- 202values <- c(1, 2, 3)values this step20startvalues ← 1, 2, 3
1start <- 202values <- c(1, 2, 3)3total <- Reduce(`+`, values, init = start)values this step1, 2, 3valuestotal ← 26
2values <- c(1, 2, 3)3total <- Reduce(`+`, values, init = start)4label <- paste("total", total, sep = ":")values this step26total20start1, 2, 3valueslabel ← total:26
3total <- Reduce(`+`, values, init = start)4label <- paste("total", total, sep = ":")5cat(label, "\n", sep = "")values this steptotal:26label26totalcat(label, " ", sep = "")
4label <- paste("total", total, sep = ":")5cat(label, "\n", sep = "")outputtotal:26values this steptotal:26label
initial value
`init` gives the reduction a starting accumulator.
combine
`+` combines the accumulator with each value.
reduce
`Reduce` returns one accumulated result.