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

后端 未结 7 1850
抹茶落季
抹茶落季 2021-01-04 07:56

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 structure

7条回答
  •  孤独总比滥情好
    2021-01-04 08:29

    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.

提交回复
热议问题