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

2

5

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

Alvey answered 5/10, 2012 at 19:45 Comment(0)
S
10

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.

Scoop answered 5/10, 2012 at 20:3 Comment(1)
Thank you both, Tilman and Rob. After stumbling around a bit on my own I figured out the list comprehension. I'd tried to figure out a keyfind solution, but didn't understand how to access the field. Do much appreciate your help, guys.Alvey
A
6

You also could use a list comprehension, like

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

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

Autecology answered 5/10, 2012 at 21:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.