[erlang-questions] Dynamically access record fields

Loïc Hoguin <>
Tue Feb 12 14:01:58 CET 2013


On 02/12/2013 01:43 PM, Dmitry Belyaev wrote:
>> g(bindings, #http_req{bindings=Ret}) -> Ret;
>> g(body_state, #http_req{body_state=Ret}) -> Ret;
>> g(buffer, #http_req{buffer=Ret}) -> Ret;
>> g(connection, #http_req{connection=Ret}) -> Ret;
>> g(cookies, #http_req{cookies=Ret}) -> Ret;
>> g(fragment, #http_req{fragment=Ret}) -> Ret;
>> g(headers, #http_req{headers=Ret}) -> Ret;
>> g(host, #http_req{host=Ret}) -> Ret;
>> g(host_info, #http_req{host_info=Ret}) -> Ret;
>> g(meta, #http_req{meta=Ret}) -> Ret;
>> g(method, #http_req{method=Ret}) -> Ret;
>> g(multipart, #http_req{multipart=Ret}) -> Ret;
>> g(onresponse, #http_req{onresponse=Ret}) -> Ret;
>> g(p_headers, #http_req{p_headers=Ret}) -> Ret;
>> g(path, #http_req{path=Ret}) -> Ret;
>> g(path_info, #http_req{path_info=Ret}) -> Ret;
>> g(peer, #http_req{peer=Ret}) -> Ret;
>> g(pid, #http_req{pid=Ret}) -> Ret;
>> g(port, #http_req{port=Ret}) -> Ret;
>> g(qs, #http_req{qs=Ret}) -> Ret;
>> g(qs_vals, #http_req{qs_vals=Ret}) -> Ret;
>> g(resp_body, #http_req{resp_body=Ret}) -> Ret;
>> g(resp_headers, #http_req{resp_headers=Ret}) -> Ret;
>> g(resp_state, #http_req{resp_state=Ret}) -> Ret;
>> g(socket, #http_req{socket=Ret}) -> Ret;
>> g(transport, #http_req{transport=Ret}) -> Ret;
>> g(version, #http_req{version=Ret}) -> Ret.
>
> It is possible to write:
>
> -record(record1, {a, b, c}).
> -record(record2, {c, b, a}).
>
> g(Field, #record1{} = Record) ->
>      g(Field, Record, record_info(fields, record1), 2);
> g(Field, #record2{} = Record) ->
>      g(Field, Record, record_info(fields, record2), 2).
>
> g(Field, Record, [Field | _], I) ->
>      element(I, Record);
> g(Field, Record, [_ | Fields], I) ->
>      g(Field, Record, Fields, I + 1);
> g(_, _, _, _) ->
>      error(badarg).

Yes, you can write this, but copy pasting clauses was much faster to 
write and a lot less prone to bugs.

-- 
Loïc Hoguin
Erlang Cowboy
Nine Nines
http://ninenines.eu



More information about the erlang-questions mailing list