Rafraîchissoir

By Shahed Nooshmand

Perl Weekly Challenge: week 57

One-liners, once more.

Task #1

This is an easy one: invert a full binary tree.

raku -e 'say (sub ($_) { .isa(Pair) ?? (.key => reverse .value.map: { samewith $^a }) !! $_ })(1 => (2 => (4, 5), 3 => (6, 7)))'

It’s not even that complicated. We write an anonymous subroutine (call it λ if you want) that checks if the input is a parent-children Pair in which case it reverses the children, or is not a Pair and returns the input as is. This is the same notation as last week’s binary tree problem.

You’ll note the use of samewith for recursive calls. Every child itself has to go through the same anonymous subroutine, and samewith does just that.

Task #2

Write a script to find the shortest unique prefix for each each word in the given list. The prefixes will not necessarily be of the same length.

Here’s one way to do it:

raku -e 'say (my @words = get.words).map: { m« ^.+? <?{1 == @words.grep: *.starts-with: ~$/}> » ?? ~$/ !! Nil }'

The regex matches the first few characters of each string minimally until it finds a prefix that’s not found in anything else. If no unique prefix is found, Nil is returned. So for this:

blue black orange brown brownish

We get this:

(blu bla o Nil browni)

Which does it for this week.