Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Reduction

The reduce routine

When you want to reduce with a custom operation rather than a single named operator, use the reduce routine. It takes a block of two arguments and applies it across the list, carrying the running result forward:

say (1..5).reduce(* + *); # 15

The block * + * has two Whatever stars: the first is the result so far, the second is the next element. So reduce computes ((((1 + 2) + 3) + 4) + 5), that is 15 — the same as [+], but written as a block.

Because the block can be anything, reduce is more general. For example, build a value step by step:

say (1..4).reduce(-> $acc, $x { $acc * 10 + $x }); # 1234

Each step multiplies the accumulator by ten and adds the next digit, turning the separate digits 1, 2, 3, 4 into the number 1234.

In short, [op] is the quick form for a named operator, and reduce is the flexible form for an arbitrary combining block. Both fold a list down to a single value.

Practice

Complete the quiz that covers the contents of this topic.

Course navigation

Quiz — The reduce metaoperator   |   Quiz — Reduction


💪 Or jump directly to the exercises in this section.