[erlang-questions] Getting the position of a list item

Igor Ribeiro Sucupira <>
Wed Dec 2 18:53:04 CET 2009


I happened to need that once and ended up implementing my own, so I
think you won't find it in the standard library.

Later, I realized there was a more elegant way of doing what I wanted,
so I should agree with Robert in that you probably don't need that
functionality (but we could be wrong, of course...).

find_first(Element, List) when is_list(List) ->
    find_first(Element, List, 0).

find_first(_Element, [], Inc) when is_integer(Inc) ->
    Inc + 1;
find_first(Element, [Element | _Tail], Inc) when is_integer(Inc) ->
    Inc + 1;
find_first(Element, [_ | Tail], Inc) when is_integer(Inc) ->
    find_first(Element, Tail, Inc + 1).


Igor.

On Wed, Dec 2, 2009 at 3:10 PM, Garrett Smith <> wrote:
> I'm missing something basic here :\
>
> The lists module has keyfind/3 but no find/2, where you want to return
> the position of a particular list item. This is surprising.
>
> Is there a commonly used pattern for this?
>
> Garrett

-- 
"The secret of joy in work is contained in one word - excellence. To
know how to do something well is to enjoy it." - Pearl S. Buck.


More information about the erlang-questions mailing list