Search code examples
listerlangrecords

In Erlang, how can I return an entire record from a list of records given an id value?


I see related issues and solutions in Google and in previous answers here, but they all baffle me.

Say I have a list of records, each with an id. Say:

-record(blah, {id, data}).
 Record2#blah.id = 7
 L = [Record1, Record2, ... ]

I'm looking for a function like get_record(List, ID) that will return the corresponding record in it's entirety, e.g.:

22> get_record(L, 7).
{blah, id=7, data="ta da!"}

Many thanks,

LRP

I


Solution

  • Internally, a record is a tuple of {Name, v1, v2}, so your example record will look like {blah, 7, data} as a tuple.

    With this in mind, you can use the lists:keyfind/3 function to look up a record in a list:

    lists:keyfind(7, #blah.id, L).
    

    The first argument here is ID value, the second argument is the tuple index for the ID field and the third argument is the list.

    The #Name.Field syntax allows you to get the field index for any record field.