Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace keys in a tuple in Erlang

Tags:

tuples

erlang

I have a list of tuples eg. [{1,40},{2,45},{3,54}....{7,23}] where 1...7 are days of the week (calculated by finding calendar:day_of_the_week()). So now I want to change the list to [{Mon,40},{Tue,45},{Wed,54}...{Sun,23}]. Is there an easier way to do it than lists:keyreplace?

like image 443
Sushant Avatar asked Oct 01 '08 10:10

Sushant


2 Answers

... or using a different syntax:

[{httpd_util:day(A), B} || {A,B} <- L]

where:

L = [{1,40},{2,45},{3,54}....{7,23}]

The construct is called a list comprehension, and reads as:

"Build a list of {httpd_util:day(A),B} tuples, where {A,B} is taken from the list L"

like image 199
uwiger Avatar answered Nov 15 '22 18:11

uwiger


Simple. Use map and a handy tool from the httpd module.

lists:map(fun({A,B}) -> {httpd_util:day(A),B} end, [{1,40},{2,45},{3,54},{7,23}]).
like image 26
Jon Gretar Avatar answered Nov 15 '22 20:11

Jon Gretar