Eugene Barsky
Eugene Barsky

Reputation: 6012

How to check that all elements of an array are defined in Perl 6?

> so (Any)
False

But

> so [1, Any]
True

How to make it produce False?

UPD: This seems to work, though I'm not sure it's the right way.

> so [1, Any].all
False

Upvotes: 3

Views: 320

Answers (2)

timotimo
timotimo

Reputation: 4329

If you want definedness rather than truthyness checks, you can also say [1, 2, Any].all.defined, which will autothread the defined method call over the junction.

say [1, 2, True].all.defined   # True
say [1, Int, True].all.defined # False

Upvotes: 2

Elizabeth Mattijsen
Elizabeth Mattijsen

Reputation: 26924

First of all, (Any) is not a List, (Any,) is (note the comma). You should either make the first case an array (like [Any]). Otherwise you're comparing apples with oranges :-)

When you give so a list (lowercase list meaning an Array or a List in this context), it will take the number of elements in the list: so every list that has at least one element, will give True.

To answer your question, there are many ways of doing that, but all will require at least partial walking of the list. If you are sure that your list does not contain 0 or the empty string, you could do something as simple as:

say so [&&] (1,Any,3); # False
say so [&&] (1,2,3);   # True

The [&&] is basically saying: 1 && Any && 3 and 1 && 2 && 3.

If you cannot be sure of that, then you will have to do an additional step:

say [&&] (1,Any,3).map: *.defined; # False
say [&&] (1,0,3).map: *.defined;   # True

Note that in this case you don't have to do the so, as the .map already makes the values either True or False. I'm leaving it as an exercise for the reader to do something faster using .first.

Upvotes: 6

Related Questions