As a simple example, suppose I have a list of numbers L
and I want to find the first element that is greater than some specific number X
. I could do this with list comprehensions like this:
(mynode@127.0.0.1)24> L = [1, 2, 3, 4, 5, 6].
[1,2,3,4,5,6]
(mynode@127.0.0.1)25> X = 2.5.
2.5
(mynode@127.0.0.1)26> [First | _] = [E || E <- L, E > X].
[3,4,5,6]
(mynode@127.0.0.1)27> First.
3
But this seems potentially very inefficient, since the list could be very long and the first match could be early on. So I'm wondering whether either a) Is there an efficient way to do this that won't evaluate the rest of the elements in the list after the first match is found? or b) When this gets compiled, does Erlang optimize the rest of the comparisons away anyways?
This is how I would achieve what I'm looking for in C:
int first_match(int* list, int length_of_list, float x){
unsigned int i;
for(i = 0; i < length_of_list, i++){
if(x > list[i]){ return list[i]; } /* immediate return */
}
return 0.0; /* default value */
}
well, something like
Here's a quick solution:
Here's what I was able to come up with. I'd still like to know if there's a better answer and/or if the simplest thing gets optimized (the more I think about it, the more I doubt it).
Example:
Edit
Here's a version without an accumulator.