Skip to content

Instantly share code, notes, and snippets.

@dduugg
Created May 24, 2020 01:19
Show Gist options
  • Save dduugg/b2ef2835429edd9777f10848c87b87c3 to your computer and use it in GitHub Desktop.
Save dduugg/b2ef2835429edd9777f10848c87b87c3 to your computer and use it in GitHub Desktop.
Higher-order functions in practice
-module(hof).
-export([doubleAll/1, evens/1, product/1, test/0]).
doubleAll(Xs) -> lists:map(fun (X) -> 2 * X end, Xs).
doubleAll_test() ->
[] = doubleAll([]),
[2] = doubleAll([1]),
[0, 6] = doubleAll([0, 3]),
ok.
evens(Xs) ->
lists:filter(fun (X) -> X rem 2 == 0 end, Xs).
evens_test() ->
[] = evens([]),
[] = evens([1, 3, 5]),
[2, 4] = evens([1, 2, 3, 4]),
ok.
product(Xs) ->
lists:foldr(fun (X, Acc) -> Acc * X end, 1, Xs).
product_test() ->
1 = product([]),
2 = product([2]),
6 = product([2, 3]),
ok.
zip([], _) -> [];
zip(_, []) -> [];
zip([X | Xs], [Y | Ys]) -> [{X, Y}] ++ zip(Xs, Ys).
zip_test() ->
[{1, 2}, {3, 4}] = zip([1, 3, 5, 7], [2, 4]), ok.
zip_with(_, [], _) -> [];
zip_with(_, _, []) -> [];
zip_with(Func, [X | Xs], [Y | Ys]) ->
[Func(X, Y)] ++ zip_with(Func, Xs, Ys).
zip_with_test() ->
[3, 7] = zip_with(fun (X, Y) -> X + Y end, [1, 3, 5, 7],
[2, 4]),
ok.
zip_with_alt(Func, Xs, Ys) ->
lists:map(fun ({X, Y}) -> Func(X, Y) end, zip(Xs, Ys)).
zip_with_alt_test() ->
[3, 7] = zip_with_alt(fun (X, Y) -> X + Y end,
[1, 3, 5, 7], [2, 4]),
ok.
zip_alt(Xs, Ys) ->
zip_with(fun (X, Y) -> {X, Y} end, Xs, Ys).
zip_alt_test() ->
[{1, 2}, {3, 4}] = zip_alt([1, 3, 5, 7], [2, 4]), ok.
test() ->
doubleAll_test(),
evens_test(),
product_test(),
zip_test(),
zip_with_test(),
zip_with_alt_test(),
zip_alt_test(),
ok.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment