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

邮差的信 提交于 2020-04-10 08:00:10

问题


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 $things, 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?


回答1:


Depends on what your definition of "best" or "smart" is.

If you're talking about performance, I'm pretty sure

@stuff.first($thing)

is the fastest.

Idiomatically, and close to the above solution, would be:

$thing ~~ any @stuff

which has the potential of better wallclock performance due to auto-threading.

Using sets to do this, makes the code look closer to formal logic. But it won't make things faster, because the set needs to be created (unless maybe it could be created at compile time).

Not sure there is a "best" answer to this one.



来源:https://stackoverflow.com/questions/41763453/perl-6-whats-the-best-way-to-check-if-an-element-is-in-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!