Skip to content

Instantly share code, notes, and snippets.

@chreke
Created November 23, 2012 08:14
Show Gist options
  • Save chreke/4134487 to your computer and use it in GitHub Desktop.
Save chreke/4134487 to your computer and use it in GitHub Desktop.
Build tree from proplist with list keys
-module(trees).
-export([build_tree/1]).
%% @doc Builds a (proplist-based) tree from a proplist where each key
%% is a list of keys.
build_tree(Proplist) ->
build_tree(Proplist, []).
build_tree([], Tree) ->
Tree;
build_tree([{Keys, Value} | Proplist], Tree) ->
build_tree(Proplist, insert_value(Keys, Value, Tree)).
insert_value([Key], Value, Tree) ->
[{Key, Value} | Tree];
insert_value([Key | Keys], Value, Tree) ->
Subtree = proplists:get_value(Key, Tree, []),
update_value(Key, insert_value(Keys, Value, Subtree), Tree).
update_value(Key, Value, Proplist) ->
[{Key, Value} | proplists:delete(Key, Proplist)].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment