Created
September 13, 2011 12:41
-
-
Save gdamjan/1213721 to your computer and use it in GitHub Desktop.
Erlang macro to create proplist_to_record functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%%% 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). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://gist.github.com/1272771 for a macro/fun to make a proplist out of record