Erlang lists:index_of function?

后端 未结 6 1960
臣服心动
臣服心动 2020-12-10 01:58

I\'m looking for an Erlang library function that will return the index of a particular element in a list.

So, if

<         


        
6条回答
  •  感情败类
    2020-12-10 02:33

    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.

提交回复
热议问题