[erlang-questions] Modify a list of tuples

Lev Walkin vlm@REDACTED
Thu Aug 14 23:43:35 CEST 2008


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.


(fun(L, Property, Value) ->
	[T || TS <- L, T <- [
	    [{K, Value}
		|| {K, V} <- TS,
		Value <- [case K of Property -> Value; _ -> V end]
	    ]
	]
	]
end)([ [{a,1},{b,2}], [{b,3},{a,4}] ], b, 'CHANGED').

=== cut ===
Eshell V5.6.3  (abort with ^G)
1> (fun(L, Property, Value) -> [T || TS <- L, T <- [[{K, Value} || {K, 
V} <- TS, Value <- [case K of Property -> Value; _ -> V end]]] ] end)([ 
[{a,1},{b,2}], [{b,3},{a,4}] ], b, 'CHANGED').
[[{a,1},{b,'CHANGED'}],[{b,'CHANGED'},{a,4}]]
2>
=== cut ===

-- 
vlm



More information about the erlang-questions mailing list