假设有个列表L:
1>L = [1,2,3,4,5].
[1,2,3,4,5]
现在想把列表中每个元素加倍,
2>lists:map(fun(X) -> 2*X end, L).
[2,4,6,8,10]
现在有个更简练的方式:
4> [2*X || X <- L ].
[2,4,6,8,10]
记号[ F(X) || X <- L ]代表“由F(X)组成的列表,其中X是取值于列表L”. 因此, [2*X || X <- L]表示“列表L中每一个元素X乘以2后的列表”。又如:
7> Buy=[{oranges,4}, {newspaper,1},{apples,10}, {pears,6},{milk,3}].
[{oranges,4},{newspaper,1},{apples,10},{pears,6},{milk,3}]
8> [{Name,2*Number} || {Name, Number} <- Buy].
[{oranges,8},{newspaper,2},{apples,20},{pears,12},{milk,6}]
阅读(1885) | 评论(0) | 转发(0) |