Erlang:匹配一些条件的列表中的第一个元素(不评估其余元素) [英] Erlang: First element in a list matching some condition (without evaluating the rest of the elements)

查看:182
本文介绍了Erlang:匹配一些条件的列表中的第一个元素(不评估其余元素)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个简单的例子,假设我有一个数字列表 L ,我想找到大于某个特定数字的第一个元素X 。我可以通过列表推导这样做:

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

但这似乎可能非常低效,因为列表可能很长,第一场比赛可能很早。所以我想知道是否a)有没有一个有效的方法来做这个,不会评估列表中的其余的元素在第一个匹配后找到?或者b)编译时,Erlang会优化其余的比较吗?

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?

这是我将如何实现我在C中寻找的东西:

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


推荐答案

好吧,像

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

这篇关于Erlang:匹配一些条件的列表中的第一个元素(不评估其余元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆