[erlang-questions] Getting the position of a list item
Andrew Thompson
andrew@REDACTED
Wed Dec 2 18:50:40 CET 2009
On Wed, Dec 02, 2009 at 11:10:25AM -0600, 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?
>
gen_leader has a compact little function I've 'borrowed' a couple times:
pos(_, []) ->
100000;
pos(N1,[N1|_]) ->
1;
pos(N1,[_|Ns]) ->
1+pos(N1,Ns).
I agree that something like this would be handy to have in the stdlib
(I've also written a version that finds the index of the first element
that a predicate fun returns true for).
Andrew
More information about the erlang-questions
mailing list