Perl 6: what's the best way to check if an item is in a list?

Let's say I have a large array @stuffand $thingand I want to know if is $thingin @stuff. What is the best way to do this in Perl 6? And with the β€œbest,” I mean: idiomatic, readable, performing; not necessarily in that order.

In fact, there are two separate cases. One of them is where you need to do a lot of checks for different $things, the other is where you do it only once or several times.

Let's look at the first case first. I think I know (or) the correct answer.

my $set-of-stuff = set @stuff;
for @whatever -> $thing {
    do-something-with($thing) if $thing ∈ $set of stuff;
}

You can skip the first line and just say it ... if $thing ∈ @stuff, but it will almost certainly have much worse performance as the set is created every time.

But now in the second case, I have only one $thingfor verification. The above solution works, of course, but creating a set just to test it once seems a lot of overhead. Label

do-something-with($thing) if $thing ∈ @stuff;

makes a little more sense here, since we call it only once. But still we need to create a kit for one use.

Somewhat more traditional is:

do-something-with($thing) if @stuff.grep($thing);

Or potentially faster:

do-something-with($thing) if @stuff.first($thing);

But this seems less idiomatic, and, of course, the second is less readable than $thing ∈ @stuff.

I don’t think there is a solution for smart matching, right? Of course this does not work:

do-something-with($thing) if $thing ~~ @stuff;

Any thoughts?

+6
source share
1 answer

Depending on your definition of "best" or "smart."

, ,

@stuff.first($thing)

.

:

$thing ~~ any @stuff

- .

. , (, , ).

, .

+11

Source: https://habr.com/ru/post/1014252/


All Articles