tags:

views:

75

answers:

2

Say you have an Erlang record of the following kind for songs:

rd(song, {artist, title, album}).
Song = #song{artist = <<"oasis">>, title = <<"wonderwall">>, album = <<"morning glory">>}.

But you want to reformat the song records to include only the artist and title. How would you go about removing a field in Erlang records (in this case album)?

+5  A: 

In one sense you can't as records are all done at compiletime so they don't really exist as such. You're #song record becomes the tuple {song,Artist,Title,Album}. It is defined like that. See Erlang -- Records. What you have to do is define a new #song record and manually convert all your songs, i.e. create new tuples. Remember all data is immutable.

There have been a number of suggestions to implement a more dynamic field object but none have been accepted yet.

Read the Erlang documentation it is generally quite good.

rvirding
Do you think ordered dictionaries are more appropriate?
Ted Karmel
If you are working on small number of elements using proplists should be pretty efficient. Proplists are list of 2-element tuples like this: `[{artist, "Queen"}, {song, "We Will Rock You"}, {album, "News Of The World"}]`
gleber
A proplist would be fine for the data of each song. It would be a bit slower, but would be much more dynamic. The same goes for using an ordered dictionary, or any other form of dictionary for that matter. `orddict` would behave much the same as `proplist` for what you are doing. Don't use `dict` for this as the overhead for an empty dict is larger and you probably won't have that much data for each song. The question is then how you store the data of all the songs and how you index them. For this `dict` would be reasonable, or an ets table.
rvirding
A: 

And if you really, really want to actually remove a field from the existing record tuples it is possible.

You can use the tuple_to_list and list_to_tuple functions, and maybe the #song.title syntax to get the index of the field, remove it from the list and convert back to a tuple.

But its probably not a good idea.

Lii