http://www.perlmonks.org?node_id=927681


in reply to An exploration of higher-level-language approaches to the "First all-zero row in an NxN matrix" problem (goto Considered Harmful)

My first impulse was to write basically the List::MoreUtils solutions in Perl 6. It has all() and .all built in, but no firstidx, so the solution goes through the detour of creating (index => value) pairs first:

my @array = [ qw/ 1 1 1 1 1 / ], [ qw/ 0 1 1 0 0 / ], [ qw/ 0 0 0 0 1 / ], [ qw/ 0 0 0 0 0 / ], [ qw/ 0 1 0 -1 0 / ], ; say @array.pairs.first({.value.all == 0 }).key;

Now .all == 0 should ring a bell for Perl 6 developers, there's a simplification around the corner:

say @array.pairs.first(*.value.none).key;

A good solution always plays to the strength of the language that it is implemented in. If Perl 6 didn't have junctions, I'd go the route of calculating the sum instead, which is readily available:

say @array.pairs.first({ 0 == [+] .value.list}).key;

(This assumes that no negative entries are allowed. If they are allowed, one could add a >>.abs after the .list to fix it).

Another approach is to use the fact that 0 is the only number that evaluates to False in boolean context:

say @array.pairs.first({ not [||] .value.list}).key;

In both cases I make use of the fact that [op] applies the operator op to a list of values.

  • Comment on Re: An exploration of higher-level-language approaches to the "First all-zero row in an NxN matrix" problem (goto Considered Harmful)
  • Select or Download Code