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

I see related problems and solutions on Google and in previous answers here, but they all puzzle me.

Say I have a list of entries, each with an identifier. Say:

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

I am looking for a function, such as get_record (List, ID), which will return the entire record to it, for example:

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

Thank you very much,

Lrp

I

+4
source share
2 answers

Internally, the record is a tuple {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 search for an entry in a list:

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

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

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

+9
source

You can also use list comprehension like

 [R || R <- Records, R#blah.id == 7] 

which will give you all the entries in the list that match the id.

+5
source

Source: https://habr.com/ru/post/1438079/


All Articles