Reputation: 289
Is there a way how to test whether an element exists in list?
$ qore -nX 'boolean(select ("a", "b", "c"), $1 === "a")'
This solution creates a new list only to test its size...
Upvotes: 1
Views: 39
Reputation: 289
There is actually a language function for this! inlist and inlist_hard
Upvotes: 0
Reputation: 730
If the elements are not repeated, then your solution is not bad, as only a single element list would be returned.
For a more efficient general solution, you can use the foldl and map operators together, both of which support lazy functional evaluation, so no intermediate lists will be created during the execution of the compound expression.
For example:
$ qore -nX '(foldl $1 + $2, (map 1, ("a", "b", "c", "a"), $1 === "z")).toBool()'
False
$ qore -nX '(foldl $1 + $2, (map 1, ("a", "b", "c", "a"), $1 === "a")).toBool()'
True
Note that you can take away the .toBool() pseudo-method call in the above expressions to get the count of occurrences of the element in the list directly. One drawback of this solution, however, is that it scans the entire list instead of stopping as soon as the first match is found.
Upvotes: 1