Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: First element in a list matching some condition (without evaluating the rest of the elements)

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 */
}
like image 623
dantswain Avatar asked Sep 29 '12 22:09

dantswain


2 Answers

well, something like

firstmatch(YourList, Number) -> 
   case lists:dropwhile(fun(X) -> X =< Number end, YourList) of
     [] -> no_solution;
     [X | _] -> X
   end.
like image 85
Odobenus Rosmarus Avatar answered Nov 09 '22 03:11

Odobenus Rosmarus


Here's a quick solution:

first_greater([],_) -> undefined;
first_greater([H|_], Num) when H > Num -> H;
first_greater([_|T], Num) -> first_greater(T,Num).
like image 26
chops Avatar answered Nov 09 '22 02:11

chops