Quick Trick: Longest string using the reduction operator

I had a problem where I wanted the longest string from a list. I didn’t want to sort because I wanted to do it with a single pass. (The comments show sorting through max, which I was also avoiding).

# quote words, but with quote protection!
my @strings = qww/
	"This is a line"
	short
	"A very very long string maybe, certainly the longest"
	other
	not
	this
	a
	one
	or
	even
	1
	/;

# If you give one thing to sort, it does that to both things and
# compares with camp
my ($longest) = @strings.sort( *.chars ).[*-1];

Instead, I decided to use the [reduction operator](https://docs.perl6.org/language/operators#Reduction_Operators) with an operator that I make up (and limit to the lexical scope). The infix longest takes two strings and returns the longest. I let the reduction take care of the rest:

my sub infix: { $^a.chars > $^b.chars ?? $^a !! $^b }
my $longest = [longest] @strings;

say "Longest is 「$longest」";

Some commenters point out that calling .max does the same thing. Looking in the Rakudo source for max, you see that it’s single pass too:

my $longest = @strings.max: *.chars;
say "Longest is 「$longest」";

2 comments

Leave a Reply

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