How to Search for an item in a List in Erlang?

2019-02-12 07:58发布

I am writing a cache gen-server for the company Use. I am wondering how to search an item from the list as I want the cost of the search for comparing various data structures in erlang like dict, orddict, List, tuples, tree, queue etc to use for cache program.

Example:

List = [{"A1",["ankit","sush", "Hover", "x4", "a3","nilesh","mike","erlang" | ...]}|...].

Now, I want to search for the Key A1 and search for 'mike' in the list. What is the best way to search the above List.

Please provide some examples. Atleast Pseudo for it.

7条回答
Viruses.
2楼-- · 2019-02-12 08:56

If you want this kind of "List" you can easily hand craft your own search:

search_key(Key, [{Key,_}=V|_]) -> {ok, V};
search_key(Key, [_|T]) -> search_key(Key, T);
search_key(_, []) -> not_found.

search_val(Val, [{_,L}=X|T]) ->
  case _search_val(Val, L) of
    ok -> {ok, X};
    not_found -> search_val(Val, T)
  end;
search_val(_, []) -> not_found.

_search_val(Val, [Val|_])-> ok;
_search_val(Val, [_|T])-> _search_val(Val, T);
_search_val(_,[])-> not_found.

But I'm not sure what exactly you want. For example if you want search for key "A1" and than for value "mike" in the list, it will be different solution. And if you want know how store this sort in best structure it is just another one question. You should provide more information.

查看更多
登录 后发表回答