Skip to content

Instantly share code, notes, and snippets.

@gdamjan
Created September 13, 2011 12:41
Show Gist options
  • Save gdamjan/1213721 to your computer and use it in GitHub Desktop.
Save gdamjan/1213721 to your computer and use it in GitHub Desktop.
Erlang macro to create proplist_to_record functions
%%% This is a clever Erlang macro that given a record name will create a new function
%%% that converts from a property list to the record (which really is a taged tuple).
-define(proplist_to_record(Record),
fun(Proplist) ->
Fields = record_info(fields, Record),
[Tag| Values] = tuple_to_list(#Record{}),
Defaults = lists:zip(Fields, Values),
L = lists:map(fun ({K,V}) -> proplists:get_value(K, Proplist, V) end, Defaults),
list_to_tuple([Tag|L])
end
).
-record(foo, {bar = "baz", camp = "spam"}).
test() ->
PropList = [{bar, "hello"}],
Fun = ?proplist_to_record(foo),
Fun(PropList).
@gdamjan
Copy link
Author

gdamjan commented Oct 10, 2011

See also https://gist.github.com/1272771 for a macro/fun to make a proplist out of record

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment