Skip to content

Commit

Permalink
Merge pull request #900 from basho/fix-riak_core_util-compose
Browse files Browse the repository at this point in the history
Fix riak_core_util:compose functions
  • Loading branch information
jvoegele committed Mar 17, 2017
2 parents 10e8b44 + f3ab66e commit 3f53928
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions src/riak_core_util.erl
Original file line number Diff line number Diff line change
Expand Up @@ -360,19 +360,22 @@ multi_keydelete(KeysToDelete, N, TupleList) ->

%% @doc Function composition: returns a function that is the composition of
%% `F' and `G'.
-spec compose(fun(), fun()) -> fun().
compose(F, G) when is_function(F), is_function(G) ->
-spec compose(F :: fun((B) -> C), G :: fun((A) -> B)) -> fun((A) -> C).
compose(F, G) when is_function(F, 1), is_function(G, 1) ->
fun(X) ->
F(G(X))
end.

%% @doc Function composition: returns a function that is the composition of all
%% functions in the `Funs' list.
-spec compose([fun()]) -> fun().
%% functions in the `Funs' list. Note that functions are composed from right to
%% left, so the final function in the `Funs' will be the first one invoked when
%% invoking the composed function.
-spec compose([fun((any()) -> any())]) -> fun((any()) -> any()).
compose([Fun]) ->
Fun;
compose([Fun|Funs]) ->
lists:foldl(fun compose/2, Fun, Funs).
compose(Funs) when is_list(Funs) ->
[Fun|Rest] = lists:reverse(Funs),
lists:foldl(fun compose/2, Fun, Rest).

%% @doc Invoke function `F' over each element of list `L' in parallel,
%% returning the results in the same order as the input list.
Expand Down Expand Up @@ -962,8 +965,22 @@ compose_test_() ->
Upper = fun string:to_upper/1,
Reverse = fun lists:reverse/1,
Strip = fun(S) -> string:strip(S, both, $!) end,
Composed = compose([Upper, Reverse, Strip]),
?_assertEqual("DLROW OLLEH", Composed("Hello world!")).
StripReverseUpper = compose([Upper, Reverse, Strip]),

Increment = fun(N) when is_integer(N) -> N + 1 end,
Double = fun(N) when is_integer(N) -> N * 2 end,
Square = fun(N) when is_integer(N) -> N * N end,
SquareDoubleIncrement = compose([Increment, Double, Square]),

CompatibleTypes = compose(Increment,
fun(X) when is_list(X) -> list_to_integer(X) end),
IncompatibleTypes = compose(Increment,
fun(X) when is_binary(X) -> binary_to_list(X) end),
[?_assertEqual("DLROW OLLEH", StripReverseUpper("Hello world!")),
?_assertEqual(Increment(Double(Square(3))), SquareDoubleIncrement(3)),
?_assertMatch(4, CompatibleTypes("3")),
?_assertError(function_clause, IncompatibleTypes(<<"42">>)),
?_assertError(function_clause, compose(fun(X, Y) -> {X, Y} end, fun(X) -> X end))].

pmap_test_() ->
Fgood = fun(X) -> 2 * X end,
Expand Down

0 comments on commit 3f53928

Please sign in to comment.