[erlang-questions] Modify a list of tuples

Richard A. O'Keefe <>
Fri Aug 15 08:11:35 CEST 2008

On 15 Aug 2008, at 9:06 am, Dave Bryson wrote:

> 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}] ]
> I want to preserve the structure of the list and change a value on all
> the tuples with a given key. So for example, change all the values on
> the "b" tuple so the result would be:
> [ [{a,1},{b,CHANGED}], [{b,CHANGED},{a,4}] ]
> I've tried list comprehension but can't get it to preserve the rest of
> the list.

I am supposing that
    your-data = list of (list of (tuple with key and value))
and that you want to copy such a data structure
replacing {b, X} by {b, f(X)} for some f.

List comprehension is indeed the answer,
but you will need two of them,
because you have two levels of lists.

	[ [ case Pair
               of {b,X} -> {b,f(X)}
                ; Other -> Other
	  || Pair <- Pairs ] || Pairs <- Your_Data ]

This would certainly be clearer if the 'case' were moved out of
the comprehension into another function:

     update_pair({Key,Value}, Key) -> {Key, f(Value)};
     update_pair(Other,       _  ) -> Other.

     ... [[update_pair(Pair, b) || Pair <- Pairs] || Pairs <- Your_Data]

More information about the erlang-questions mailing list