Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

include a @list->contains('element') method? #267

Open
mascip opened this issue Jun 11, 2013 · 4 comments
Open

include a @list->contains('element') method? #267

mascip opened this issue Jun 11, 2013 · 4 comments

Comments

@mascip
Copy link

mascip commented Jun 11, 2013

This is the clearest way that i've found to indicate that a list contains a given element:

use syntax 'junction';
use autobox;
sub ARRAY::contains { any( @{$[0]} ) eq $[1] };

@ingredients->contains('flour')

that's just a humble proposal

@schwern
Copy link
Contributor

schwern commented Jun 11, 2013

You can currently do that with @ingredients->first(qr/^flour$/ ) from List::Util, but that's not well documented, nor is it the best name, nor is it guaranteed to return a true value on success (it will return the first matching value which may be false).

I can think of a few things to be done which would make things better.

  • Make @a->first("string") work like @a->first( sub { $_ eq "string" } ). Also @a->grep. Currently it is an error.

The above is a general improvement to all the list searching methods.

  • Wrap contains around first, difference is contains just returns true/false.

contains is a better name for what it does.

  • Add an entry to perl5ifaq about the various ways to search an array.

If you'd like to do this yourself, it's normal Perl. You can ignore the autobox magic. first and grep are in lib/perl5i/2/ARRAY.pm

@mascip
Copy link
Author

mascip commented Jun 11, 2013

I understand that you're leaving me the choice.
If that's the case, i'll wrap contains around first. I like methods that clearly describe what they do. And i'll add it to the POD.

@myfwhite
Copy link
Contributor

Rather than using first, why not count?

@ingredients->count(0) or @ingredients->count('') returns a true value if the (false) element is contained in the array.

@mascip
Copy link
Author

mascip commented Jun 12, 2013

Because count() will iterate over the whole list, while first() will stop as soon as it finds the element.

I prefer any() over first(). It will do exactly the same things, but i find it expresses the intent better:
'if any ingredient is flour'
is clearer than
'if i find something when search for the first ingredient which is flour'
but that's me being pedantic (^c^)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants