lists:zip / zip_with / unzip etc

Vladimir Sekissov svg@REDACTED
Tue Jul 9 17:49:04 CEST 2002


From: Heinz Eriksson <heinz.eriksson@REDACTED>
Subject: lists:zip / zip_with / unzip etc
Date: Thu, 04 Jul 2002 15:56:29 +0200
Message-ID: <3D24540D.BD1BB816@REDACTED>

heinz.eriksson> 
heinz.eriksson> ziph([H1|L1],[H2|L2], Z) -> 
heinz.eriksson>     ziph(L1,L2,[{H1,H2}|Z]);
heinz.eriksson> ziph([],L2, Z) -> 
heinz.eriksson>     Z;
heinz.eriksson> ziph(L1,[], Z) -> 
heinz.eriksson>     Z.
heinz.eriksson> 
heinz.eriksson> zip(A,B) ->
heinz.eriksson>     lists:reverse(ziph(A,B,[])).

Slightly generalized version:

noname@REDACTED> listn:zipn([[1,2,3], [4,5,6], [7,8,9]]) ->
[{1,4,7},{2,5,8},{3,6,9}]

Code:

zipn(Ls) ->
    [list_to_tuple(L) || L <- listn(Ls)].

listn(Ls) ->
  [lists:reverse(L)
   || L <- foldn(fun (A, Acc) -> [A|Acc] end, [], Ls)].

foldn(_, _, []) ->
  [];
foldn(Fun, Acc0, Ls) ->
  foldn(Fun, Acc0, Ls, []).

foldn(_, _, [[]|_], Ret) ->
  lists:reverse(Ret);
foldn(Fun, Acc0, Ls, Ret) ->
  foldn(Fun, Acc0,
	[tl(L) || L <- Ls],
	[lists:foldl(Fun, Acc0, [hd(L) || L <- Ls])|Ret]
       ).

Best Regards,
Vladimir Sekissov



More information about the erlang-questions mailing list