Skip to content

Instantly share code, notes, and snippets.

@takkkun
Created May 23, 2013 10:27
Show Gist options
  • Select an option

  • Save takkkun/5635154 to your computer and use it in GitHub Desktop.

Select an option

Save takkkun/5635154 to your computer and use it in GitHub Desktop.
-module(folder).
-author("Takahiro Kondo <heartery@gmail.com>").
-export([fold/1, fold/2]).
-export([example/0]).
-define(DEFAULT_SEPARATOR, ".").
fold(Dict) ->
fold(Dict, ?DEFAULT_SEPARATOR).
fold(Dict, Separator) ->
Keys = lists:filter(fun(Key) ->
is_list(Key) and (string:str(Key, Separator) > 0)
end, Dict:fetch_keys()),
fold(Dict, Separator, Keys).
fold(Dict, _, []) ->
Dict;
fold(Dict, Separator, [Key|Keys]) ->
KeyParts = string:tokens(Key, Separator),
Value = Dict:fetch(Key),
fold(assign(Dict:erase(Key), KeyParts, Value), Separator, Keys).
assign(Dict, [KeyPart], Value) ->
Dict:store(KeyPart, Value);
assign(Dict, [KeyPart|KeyParts], Value) ->
InnerDict = case Dict:find(KeyPart) of
{ok, D} when is_tuple(D) and (element(1, D) =:= dict) -> D;
_ -> dict:new()
end,
Dict:store(KeyPart, assign(InnerDict, KeyParts, Value)).
example() ->
D1 = dict:new(),
D2 = D1:store("a.b.c", 1),
D3 = D2:store("d", 2),
D4 = fold(D3),
io:format("a.b.c => ~p~n", [dict:fetch("c", dict:fetch("b", dict:fetch("a", D4)))]),
io:format("d => ~p~n", [dict:fetch("d", D4)]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment