Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Reduction / Exercises / The longest string

Solution: The longest string

Here is a possible solution to the task.

Code

my @animals = 'cat', 'elephant', 'dog', 'fox';

say @animals.reduce(-> $a, $b { $b.chars > $a.chars ?? $b !! $a });

🦋 You can find the source code in the file longest-string.raku.

Output

elephant

Comments

  1. The block keeps the longer of its two arguments: $a is the longest string seen so far, $b is the next one, and the ternary returns whichever has more characters.

  2. reduce carries that winner forward as $a on the next call, so after walking the whole list the accumulated value is the longest string of all — elephant.

Course navigation

The longest string   |   Comma-separated list