Erlang列表:index_of函数? [英] Erlang lists:index_of function?
本文介绍了Erlang列表:index_of函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,如果
X = [10,30,50,70]
然后
列表:index_of(30,X)
将返回1等,就像 java.util.List
的 indexOf()
方法。
Erlang标准库中是否存在这样的方法?我试着看列表模块,但没有运气。或者我应该自己写?
谢谢。
解决方案
你我们必须自己定义它,如下所示:
index_of(Item,List) - > index_of(Item,List,1)。
index_of(_,[],_) - >未找到;
index_of(Item,[Item | _],Index) - >指数;
index_of(Item,[_ | Tl],Index) - > index_of(Item,T1,Index + 1)。但是,注意列表中的第N个元素是O(N),所以通常会使用一个算法通过索引访问列表将比顺序遍历列表的效率更低。
I'm looking for an Erlang library function that will return the index of a particular element in a list.
So, if
X=[10,30,50,70]
then
lists:index_of(30, X)
would return 1, etc., just like java.util.List
's indexOf()
method.
Does such a method exist in the Erlang standard lib? I tried looking in the lists module but no luck. Or should I write it myself?
Thanks.
解决方案 You'll have to define it yourself, like this:
index_of(Item, List) -> index_of(Item, List, 1).
index_of(_, [], _) -> not_found;
index_of(Item, [Item|_], Index) -> Index;
index_of(Item, [_|Tl], Index) -> index_of(Item, Tl, Index+1).
Note however that accesing the Nth element of a list is O(N), so an algorithm that often accesses a list by index will be less efficient than one that iterates through it sequentially.
这篇关于Erlang列表:index_of函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文