tags:

views:

539

answers:

2

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.

+7  A: 

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.

sepp2k
It would be more Erlang-like to return an atom like `not_found` instead of `-1`. This way, if you forget to test for this case, you get a quick error.
Alexey Romanov
Good point. Changed.
sepp2k
Also indexing could start from 1 instead of 0.
Zed
... becase lists:nth(Index, List) treats 1 as the first item.
Christian
Also good point. Changed.
sepp2k
A: 

This function is very uncommon for Erlang and this is may be reason why it is not in standard library. No one of experienced Erlang programmers need it and is discourage to use algorithms using this function. When someone needs it, can write for own purpose but this very rare occasions are not reason to include it to stdlib. Design your data structures in proper way instead of ask for this function. In most cases need of this function indicates error in design.

Hynek -Pichi- Vychodil
So what is your opinion - as an experienced Erlang programmer, I suppose - about the lists:nth and lists:nthtail functions?
Zed
That's just a ridiculous statement. You have absolutely no idea what I need this function for.
Justin
"No one of experienced Erlang programmers need it"Guess your "experienced Erlang programmers" don't tend to deal with real world problems then ?
Justin
@Justin: Well, what practical problem you are trying to solve? I wonder why Ericsson guys doesn't need this function in 1.7 million SLOC Erlang code in their code tend to include it to lists module. Well, enlighten me which for you need it.
Hynek -Pichi- Vychodil
I need to simulate N random variables, sort them, then find out which position in the sorted list the unsorted values lie.
Justin
In that case you could do Sorted = lists:sort(lists:zip(Randoms, lists:seq(1, length(Randoms)))), and then get the index of an item by lists:keyfind(Item, 1, Sorted).
Zed
Or you can even feed Sorted to a gb_tree if you access it frequently.
Zed
Thank you, @Zed
Justin
@Justin: Well, It means that mine response is exactly as I wrote. Solution is Just do it in different way and you doesn't need this function. Solution also performs better.
Hynek -Pichi- Vychodil
I guess it's just the way you say it.
Justin