Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Reduction / Exercises / Comma-separated list
Solution: Comma-separated list
Here is a possible solution to the task.
Code
my @words = 'Raku', 'is', 'fun';
say @words.reduce(-> $a, $b { "$a, $b" });🦋 You can find the source code in the file comma-separated.raku.
Output
Raku, is, funComments
Here the block builds a value instead of choosing one:
$ais the string assembled so far and$bis the next word, and"$a, $b"glues them with a comma and a space.The first call joins
'Raku'and'is'intoRaku, is; the second joins that with'fun'to giveRaku, is, fun. This is the kind of separator-aware joining the[~]metaoperator cannot express on its own.In real code you would reach for the built-in
joinmethod, which does exactly this —say @words.join(', ');prints the sameRaku, is, fun. The point of the exercise is to practise expressing the same idea as areduceblock.