Erlang lists:index_of function?

后端 未结 6 1980
臣服心动
臣服心动 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:39

    Other solutions (remark that these are base-index=1):

    index_of(Value, List) ->
       Map = lists:zip(List, lists:seq(1, length(List))),
       case lists:keyfind(Value, 1, Map) of
          {Value, Index} -> Index;
          false -> notfound
       end.
    
    index_of(Value, List) ->
       Map = lists:zip(List, lists:seq(1, length(List))),
       case dict:find(Value, dict:from_list(Map)) of
          {ok, Index} -> Index;
          error -> notfound
       end.
    

    At some point, when the lists you pass to these functions get long enough, the overhead of constructing the additional list or dict becomes too expensive. If you can avoid doing the construction every time you want to search the list by keeping the list in that format outside of these functions, you eliminate most of the overhead.

    Using a dictionary will hash the values in the list and help reduce the index lookup time to O(log N), so it's better to use that for large, singly-keyed lists.

    In general, it's up to you, the programmer, to organize your data into structures that suit how you're going to use them. My guess is that the absence of a built-in index_of is to encourage such consideration. If you're doing single-key lookups -- that's really what index_of() is -- use a dictionary. If you're doing multi-key lookups, use a list of tuples with lists:keyfind() et al. If your lists are inordinately large, a less simplistic solution is probably best.

提交回复
热议问题