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

余生颓废 提交于 2019-12-06 02:22:11

问题


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

回答1:


well, something like

firstmatch(YourList, Number) -> 
   case lists:dropwhile(fun(X) -> X =< Number end, YourList) of
     [] -> no_solution;
     [X | _] -> X
   end.



回答2:


Here's a quick solution:

first_greater([],_) -> undefined;
first_greater([H|_], Num) when H > Num -> H;
first_greater([_|T], Num) -> first_greater(T,Num).



回答3:


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.


来源:https://stackoverflow.com/questions/12657202/erlang-first-element-in-a-list-matching-some-condition-without-evaluating-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!