Erlang: First element in a list matching some cond

2019-04-09 08:36发布

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 */
}

3条回答
叛逆
2楼-- · 2019-04-09 09:00

well, something like

firstmatch(YourList, Number) -> 
   case lists:dropwhile(fun(X) -> X =< Number end, YourList) of
     [] -> no_solution;
     [X | _] -> X
   end.
查看更多
对你真心纯属浪费
3楼-- · 2019-04-09 09:06

Here's a quick solution:

first_greater([],_) -> undefined;
first_greater([H|_], Num) when H > Num -> H;
first_greater([_|T], Num) -> first_greater(T,Num).
查看更多
Viruses.
4楼-- · 2019-04-09 09:11

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).

-module(lazy_first).

-export([first/3]).

first(L, Condition, Default) ->
  first(L, [], Condition, Default).

first([E | Rest], Acc, Condition, Default) ->
  case Condition(E) of
    true -> E;
    false -> first(Rest, [E | Acc], Condition, Default)
  end;

first([], _Acc, _Cond, Default) -> Default.

Example:

14> lazy_first:first([1, 2, 3, 4, 5], fun(E) -> E > 2.5 end, 0.0).
3
15> lazy_first:first([1, 2, 3, 4, 5], fun(E) -> E > 5.5 end, 0.0).
0.0

Edit

Here's a version without an accumulator.

first([E | Rest], Condition, Default) ->
  case Condition(E) of
    true -> E;
    false -> first(Rest, Condition, Default)
  end;

first([], _Cond, Default) -> Default.
查看更多
登录 后发表回答