Another Raku one-liner

Let me demonstrate another interesting one-liner that I find to be a good addition to my last years’s book Raku One-Liners. The task was inspired by this week’s problem from the Perl Weekly Challenge.

Let me demonstrate another interesting one-liner that I find to be a good addition to my last years’s book Raku One-Liners. The task was inspired by this week’s problem from the Perl Weekly Challenge.

Here is the task. Given the string $s and a list of words @w, tell if it is possible to combine all the words (in any possible order) to get the string.

my $s = 'perlweeklychallenge';
my @w = 'weekly', 'challenge', 'perl';

Here is my one-line solution:

say $s ∈ (@w X~ @w X~ @w)

Using a couple of cross operators with the string concatenation X~, we first create a sequence consisting of all possible combinations of the given three words, and then check if the string $s is an element of that sequence.

The program prints either True (as in the given example) or False (if you modify it to exclude the possibility of building the required string).

You can notice that the solution is not really generic, and if you have a different number of elements in @w, you have to re-write the sequence constructor. There’s nothing simpler, and here is the generic solution:

say $s ∈ [X~] @w xx @w.elems

It uses the power of the reduction operator, which, being just a pair of brackets, can hold any other available operator or even a function.

Navigation to the Raku challenges post series

3 thoughts on “Another Raku one-liner”

  1. You can actually leave out the final `.elems` in that expression:

    say $s ∈ [X~] @w xx @w

    because the right-hand side of `xx` will numerify (and numerification of an Array is its number of elements) You could rightly argue that that would reduce readability. Alternately:

    say $s ∈ [X~] @w xx +@w

    but that you could rightly consider too linenoisy 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *