I'm working on this weeks PerlWChallenge.
You are given an array of integers @A. Write a script to create an array that represents the smaller element to the left of each corresponding index. If none found then use 0.
Here's my approach:
my @A = (7, 8, 3, 12, 10);
my $L = @A.elems - 1;
say gather for 1 .. $L -> $i { take @A[ 0..$i-1 ].grep( * < @A[$i] ).min };
Which kinda works and outputs:
(7 Inf 3 3)
The Infinity obviously comes from the empty grep. Checking:
> raku -e "().min.say"
Inf
But why is the minimum of an empty Seq Infinity? If anything it should be -Infinity. Or zero?
It's probably a good idea to test for the empty sequence anyway.
I ended up using
take .min with @A[ 0..$i-1 ].grep( * < @A[$i] ) or 0
or
take ( @A[ 0..$i-1 ].grep( * < @A[$i] ) or 0 ).min