Skip to content

Instantly share code, notes, and snippets.

@gorkaio
Created June 6, 2020 09:28
Show Gist options
  • Save gorkaio/8be4d427d89953effb591ae1830a486c to your computer and use it in GitHub Desktop.
Save gorkaio/8be4d427d89953effb591ae1830a486c to your computer and use it in GitHub Desktop.
-module(hof).
-export([doubleAll/1,evens/1,product/1,zip/2,zip_with/3]).
-export([test/0]).
%% Using higher-order functions
doubleAll(Xs) -> lists:map(fun(X) -> 2*X end, Xs).
doubleAll_test() ->
[] = doubleAll([]),
[2] = doubleAll([1]),
[2,4,6,8] = doubleAll([1,2,3,4]),
passed.
evens(Xs) -> lists:filter(fun(X) -> X rem 2 == 0 end, Xs).
evens_test() ->
[] = evens([]),
[] = evens([1,3,5]),
[2] = evens([2]),
[2] = evens([2,3,5]),
[2,4] = evens([1,2,3,4,5]),
passed.
product(Xs) -> lists:foldl(fun (X, P) -> X * P end, 1, Xs).
product_test() ->
1 = product([]),
2 = product([2]),
6 = product([2,3]),
passed.
%% Zipping
zip(X, Y) ->
zip(X, Y, []).
zip([], _, Ac) -> lists:reverse(Ac);
zip(_, [], Ac) -> lists:reverse(Ac);
zip([X|Xs], [Y|Ys], Ac) ->
zip(Xs, Ys, [{X,Y}|Ac]).
zip_test() ->
[] = zip([], []),
[] = zip([1,2], []),
[] = zip([], [1,2]),
[{1,2}] = zip([1], [2]),
[{1,2},{3,4}] = zip([1,3], [2,4]),
[{1,2},{3,4}] = zip([1,3,5], [2,4]),
[{1,2},{3,4}] = zip([1,3], [2,4,6]),
passed.
zip_with(F, X, Y) ->
zip_with(F, X, Y, []).
zip_with(_, [], _, Ac) -> lists:reverse(Ac);
zip_with(_, _, [], Ac) -> lists:reverse(Ac);
zip_with(F, [X|Xs], [Y|Ys], Ac) ->
zip_with(F, Xs, Ys, [F(X,Y)|Ac]).
zip_with_test() ->
[] = zip_with(fun(X,Y) -> X*Y end, [], []),
[] = zip_with(fun(X,Y) -> X*Y end, [1], []),
[] = zip_with(fun(X,Y) -> X*Y end, [], [1]),
[2] = zip_with(fun(X,Y) -> X*Y end, [2], [1]),
[2,9] = zip_with(fun(X,Y) -> X*Y end, [2,3], [1,3]),
passed.
zip_with_map(F, X, Y) ->
lists:map(fun ({A, B}) -> F(A,B) end, zip(X, Y)).
zip_with_map_test() ->
[] = zip_with_map(fun(X,Y) -> X*Y end, [], []),
[] = zip_with_map(fun(X,Y) -> X*Y end, [1], []),
[] = zip_with_map(fun(X,Y) -> X*Y end, [], [1]),
[2] = zip_with_map(fun(X,Y) -> X*Y end, [2], [1]),
[2,9] = zip_with_map(fun(X,Y) -> X*Y end, [2,3], [1,3]),
passed.
zip2(X, Y) ->
zip_with(fun(A,B) -> {A,B} end, X, Y).
zip2_test() ->
[] = zip2([], []),
[] = zip2([1,2], []),
[] = zip2([], [1,2]),
[{1,2}] = zip2([1], [2]),
[{1,2},{3,4}] = zip2([1,3], [2,4]),
[{1,2},{3,4}] = zip2([1,3,5], [2,4]),
[{1,2},{3,4}] = zip2([1,3], [2,4,6]),
passed.
%% Tests
test() ->
doubleAll_test(),
evens_test(),
product_test(),
zip_test(),
zip_with_test(),
zip_with_map_test(),
zip2_test(),
passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment