Erlang: Removing Fields in Records
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)?
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.
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 it's probably not a good idea.
精彩评论