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
elephantComments
The block keeps the longer of its two arguments:
$ais the longest string seen so far,$bis the next one, and the ternary returns whichever has more characters.reducecarries that winner forward as$aon the next call, so after walking the whole list the accumulated value is the longest string of all —elephant.