开发者

Merge and Zip with list comprehension

Want to merge [1,3,4], [2,5] -> [1,2,3,4,5] and zip [1,2,3],[4,5] -> [{1,4},{2,5}]. Its not homew开发者_如何转开发ork, i just want improve my skill in list-comprehensions. If you know any links to tricks with it, dont hesitate to submit.


1> [1,3,4] ++ [2,5].
[1,3,4,2,5]
2> lists:zip([1,2],[4,5]).
[{1,4},{2,5}]

For the zip, you can also write your own:

% zip.erl
-module(zip).
-export([zip/2]).

zip(A, B) ->
    zip(A, B, []).

zip(_, [], Result) ->
    Result;

zip([], _, Result) ->
    Result;

zip([A|ARest], [B|BRest], Result) ->
    zip(ARest, BRest, [{A, B}|Result]).

Result:

8> c(zip).
{ok,zip}
9> zip:zip([1,2,3],[4,5]).  
[{2,5},{1,4}]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜