Advertisement
Guest User

Untitled

a guest
Jun 21st, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.66 KB | None | 0 0
  1. -module(assoc).
  2. -export([new/0,from_list/1,store/3,to_list/1,fold/3,filter/2,map/2,find/2,size/1,is_key/2,erase/2]).
  3.  
  4. new()->{null}.
  5.  
  6. from_list(L) ->
  7.     foldlist(fun ({K,V}, D) -> store(K, V, D) end, new(), L).
  8. foldlist(F, Accu, [Hd|Tail]) -> foldlist(F, F(Hd, Accu), Tail);
  9. foldlist(_, Accu, []) -> Accu.
  10.  
  11. to_list(D) -> to_list_fold(D,[]).
  12. to_list_fold({null},List)-> List;
  13. to_list_fold({{K,V},Left,Right},List) -> List++[{K,V}]++to_list(Left)++to_list(Right).
  14.  
  15. fold(F, Acc, D) -> fold_assoc(F, Acc, to_list(D)).
  16. fold_assoc(_,Acc,[])->Acc;
  17. fold_assoc(F,Acc,[{Hd,Tail}|T])-> fold_assoc(F,F(Hd,Tail,Acc),T).
  18.  
  19. filter(F, D) -> filter_assoc(F,to_list(D),[]).
  20. filter_assoc(_,[],Acc)->from_list(Acc);
  21. filter_assoc(F,[{K,V}|Tail],Acc) ->
  22.     case F(K, V) of
  23.     true -> filter_assoc(F, Tail, [{K,V}|Acc]);
  24.     false -> filter_assoc(F, Tail, Acc)
  25.     end.
  26.  
  27. map(F,D) -> map_assoc(F,to_list(D),[]).
  28. map_assoc(_,[],Acc)->from_list(Acc);
  29. map_assoc(F,[{K,V}|Tail],Acc)->map_assoc(F,Tail,[{K,F(K,V)}|Acc]).
  30.  
  31. erase(Key,D)->from_list(erase_assoc(Key,to_list(D))).
  32. erase_assoc(Key, [{Key,_}|Tail]) -> Tail;
  33. erase_assoc(Key, [Hd|Tail]) -> ([Hd|erase_assoc(Key, Tail)]);
  34. erase_assoc(_, []) -> [].
  35.  
  36. find(_,{null})->error;
  37. find(Key,{{K,V},_,_}) when Key==K ->{ok,V};
  38. find(Key,{{K,_},_,Right}) when Key>K -> find(Key,Right);
  39. find(Key,{{K,_},Left,_}) when Key<K -> find(Key,Left).
  40.  
  41. store(K,V,{null})-> {{K,V},{null},{null}};
  42. store(K,V,{{Hd,Tail},Left,Right}) ->
  43.     if K>Hd -> {{Hd,Tail},Left,store(K,V,Right)};
  44.     K<Hd -> {{Hd,Tail},store(K,V,Left),Right};
  45.     K==Hd -> {{Hd,V},Left,Right}
  46.     end.
  47.  
  48. size(D) -> fold(fun (_,_,L) -> L+1 end,0,D).
  49.  
  50. is_key(Key,D) -> find(Key,D)/=error.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement