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:
([email protected])24> L = [1, 2, 3, 4, 5, 6].
[1,2,3,4,5,6]
([email protected])25> X = 2.5.
2.5
([email protected])26> [First | _] = [E || E <- L, E > X].
[3,4,5,6]
([email protected])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
firstmatch(YourList, Number) ->
case lists:dropwhile(fun(X) -> X =< Number end, YourList) of
[] -> no_solution;
[X | _] -> X
end.
Here's a quick solution:
first_greater([],_) -> undefined;
first_greater([H|_], Num) when H > Num -> H;
first_greater([_|T], Num) -> first_greater(T,Num).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With