Skip to content

Instantly share code, notes, and snippets.

@rlipscombe
Created February 25, 2015 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rlipscombe/b0ce5ad0890a1cb8fb6d to your computer and use it in GitHub Desktop.
Save rlipscombe/b0ce5ad0890a1cb8fb6d to your computer and use it in GitHub Desktop.
partitionzipwith.erl
-module(partitionzipwith).
-export([partitionzipwith/3]).
%% @doc A combination of lists:partition/2 and lists:zipwith/3.
%% Given two lists of equal length, call Combine(X, Y) for each.
%% If it returns {true, T}, then T is added to Satisfying.
%% If it returns {false, F}, then F is added to NotSatisfying.
-spec partitionzipwith(Combine, List1, List2) ->
{Satisfying, NotSatisfying}
when
Combine :: fun((X, Y) -> {true, T} | {false, F}),
List1 :: [X], List2 :: [Y],
Satisfying :: [T], NotSatisfying :: [F].
partitionzipwith(Combine, List1, List2) ->
partitionzipwith(Combine, List1, List2, [], []).
partitionzipwith(_Combine, [], [], Satisfying, NotSatisfying) ->
{lists:reverse(Satisfying), lists:reverse(NotSatisfying)};
partitionzipwith(Combine, [X | List1], [Y | List2], Satisfying, NotSatisfying) ->
case Combine(X, Y) of
{true, T} -> partitionzipwith(Combine, List1, List2, [T | Satisfying], NotSatisfying);
{false, F} -> partitionzipwith(Combine, List1, List2, Satisfying, [F | NotSatisfying])
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment