Halve an algorithm
I considered PWC #215 to be to boring to be solved because it basically requires only halve an algorithm. But that idea kept bouncing around in my head.
my @words := <abc xyz tsu> does role { has Int $.count is rw; };
@words.map({ LAST { say @words.count }; if [before] .comb { .item } else { @words.count++; Empty } });
Part 1 is a two sentence problem that can be solved with two lines, because Raku splits sorting algorithms into two smaller problems. We got infix:<before>
and infix:<after>
to describe what ordering in a list actually means. In my eyes Rosettacode proves this to be the right decision. Here, we are asked to check for sorted-ness, without actually having to sort anything. Lesser languages need to resort to loops, we can use a reduction metaop with before
to express our wish. So I either retain an element or count the miss and skip the element.
I resorted to mixing in a role because I don’t like to stack symbol declarations on one line. By getting rid of my $count
; I can stay within my 2 line limit. For the same reason I used a LAST
-phaser. By accident I bound two related things together into the same namespace, which I rather liked in the end.
So far I did not see Raku’s ordering operators in code in the wild, other then Rosettacode. To promote them, I wrote this blogpost.
I’m not sure if the reaction of map
to Empty
is an ENODOC. It might just be emergent behaviour and I shall seek wisdom in #raku-doc.
-
May 8, 2023 at 14:332023.19 Pakku – Rakudo Weekly News