Let's say I have a large array, @stuff
, and a $thing
, and I want to know if $thing
is in @stuff
. What's the best way to do that in Perl 6? And with “best” I mean: idiomatic, readable, performant; not necessarily in that order.
There are actually two separate cases. One is where you have to do a lot of checks for different $thing
s, the other is where you only do this once or a few times.
Let's look at the first case first. I think I know the (or a) right answer.
my $set-of-stuff = set @stuff;
for @whatever -> $thing {
do-something-with($thing) if $thing ∈ $set of stuff;
}
You can actually skip the first line and simply say ... if $thing ∈ @stuff
, but that will almost certainly have much worse performance, since the set is created every time.
But now the second case, I only have one $thing
to check.
The above solution works, of course, but creating the set, just to check it once, seems a lot of overhead.
The shortcut
do-something-with($thing) if $thing ∈ @stuff;
makes a little more sense here, since we only call it once. But still, we have to create a set for one use.
A bit 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 certainly the second one is less readable than $thing ∈ @stuff
.
I don't think there's a smart match solution, right? Certainly this doesn't work:
do-something-with($thing) if $thing ~~ @stuff;
Any thoughts?