[erlang-questions] Modify a list of tuples

Jay Nelson jay@REDACTED
Fri Aug 15 06:03:56 CEST 2008


Dave Bryson asked:

 > What's the best way to modify a value for a given tuple
 > in the list  below?

 > I have a large list with the following type of structure:

 > [ [{a,1},{b,2}], [{b,3},{a,4}] ]

The question you need to ask is whether duplicate
keys are allowed in any of the lists.  If not, you may be
dealing with a list of property lists and can take
advantage of the stdlib module 'proplists'.  In general,
a property list is a stack of key / value pairs, with the
most recent value for a given key being the one
closest to the beginning of the list.

Instead of "modifying" an existing value, push a new
property onto each list:

set_value(LargeList, Property, NewValue) ->
   [ [{Property, NewValue} | PList || PList <- LargeList].

The result will then return a proper value when called
with proplists:get_value/2.  Of course, every list will now
have the new property value, not just the ones that
previously had it.

If you don't want to add the value to every list, use:

set_value(LargeList, Property, NewValue) ->
   [push_unique(Property, NewValue, PList) || PList <- LargeList].

push_unique(Property, NewValue, PList) ->
   case proplists:is_defined(Property, PList) of
     true -> [ {Property, NewValue} | PList];
     false -> PList
   end.

The first approach has the advantage of requiring
no searching, and a very fast push implemented as
allocating one new list element.  The second
requires a lookup on every list, but does not add
a value if it is not already present.  You have to
decide which applies to your situation.  If you read
the proplists module documentation, you may find
that you can still use this approach when there are
multiple values for a single key.

This approach illustrates a technique that ROK
never mentions in his rebuttals to the "a list of
numbers does not make a string".  If you parse
XML into proplists, you can modify or augment
the data without searching, and therefore exceed
the performance of array-based and dedicated
string datatype approaches.

Any time you find yourself wanting to "modify" an
existing value, stop and think if that is really the best
way to accomplish the task using a functional language,
because "modification" is not the functional approach.

jay




More information about the erlang-questions mailing list