Skip to content

Instantly share code, notes, and snippets.

@dduugg
Created May 24, 2020 19:30
Show Gist options
  • Save dduugg/28db2ff55a2dbaa2bb78a26731214502 to your computer and use it in GitHub Desktop.
Save dduugg/28db2ff55a2dbaa2bb78a26731214502 to your computer and use it in GitHub Desktop.
Functions as results in practice
-module(hof2).
-export([composition/1, iteration/1, test/0, twice/2]).
composition(Fs) ->
fun (X) -> lists:foldr(fun (F, Y) -> F(Y) end, X, Fs)
end.
composition_test() ->
F = composition([fun (X) -> X * 2 end,
fun (X) -> X + 1 end]),
6 = F(2),
ok.
twice(F, X) -> F(F(X)).
twice_test() -> 18 = twice(fun (X) -> 3 * X end, 2), ok.
iteration(0) -> fun (_, X) -> X end;
iteration(N) ->
fun (F, X) -> F2 = iteration(N - 1), F2(F, F(X)) end.
iteration_test() ->
F = iteration(3), 8 = F(fun (X) -> 2 * X end, 1).
test() ->
composition_test(), twice_test(), iteration_test(), ok.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment