Skip to content

Instantly share code, notes, and snippets.

@mareknowak
Last active May 13, 2020 10:29
Show Gist options
  • Save mareknowak/980e603154895f4e9072f61ff8f8f1a0 to your computer and use it in GitHub Desktop.
Save mareknowak/980e603154895f4e9072f61ff8f8f1a0 to your computer and use it in GitHub Desktop.
Functions over lists - FP in Erlang 2.15
%% FP in Erlang 2.15
%% Defining functions over lists in practice
-module(funlists).
-export(
[ product/1 % tail recursive version
, product_direct/1 % direct version
, maximum/1 % tail recursive version
, maximum_direct/1 % direct version
, maximum_brujo/1 % both direct and tail recursive
, test/0 % test all functions
]).
%% PRODUCT
%%
%% @doc Define an Erlang function to give the product of a list of numbers
product([], Product) -> Product;
product([X|Xs], Product) ->
product(Xs, Product * X).
product([]) -> 1;
product([X|Xs]) -> product(Xs, X).
test_product() ->
1 = funlists:product([]),
8 = funlists:product([2,2,2]),
24 = funlists:product([1,2,3,4]),
ok.
product_direct([]) -> 1;
product_direct([X|Xs]) ->
X * product_direct(Xs).
test_product_direct() ->
1 = funlists:product_direct([]),
8 = funlists:product_direct([2,2,2]),
24 = funlists:product_direct([1,2,3,4]),
ok.
%% MAXIMUM
%%
%% @doc Define an Erlang function to give the maximum of a list of numbers.
maximum([], Max) -> Max;
maximum([X|Xs], Max) ->
maximum(Xs, max(Max, X)).
maximum([X]) -> X;
maximum([X,Y| Xs]) ->
maximum(Xs, max(X, Y)).
test_maximum() ->
2 = funlists:maximum([1,2,1]),
12.34 = funlists:maximum([-1, 12.34, -100, 11]),
ok.
maximum_direct([X]) -> X;
maximum_direct([X|Xs]) ->
max(X, maximum_direct(Xs)).
test_maximum_direct() ->
2 = funlists:maximum_direct([1,2,1]),
12.34 = funlists:maximum_direct([-1, 12.34, -100, 11]),
ok.
%% From Brujo Benavides
maximum_brujo([X]) -> X;
maximum_brujo([X, Y | Xs]) ->
maximum_brujo([max(X, Y) | Xs]).
test() ->
ok = test_product(),
ok = test_product_direct(),
ok = test_maximum(),
ok = test_maximum_direct(),
ok.
@elbrujohalcon
Copy link

Comma-first ROK-style!! 😍
A trick I saw in someone else's code to reduce maximum/2

maximum([X]) -> X;
maximum([X, Y | Xs]) -> maximum([max(X, Y) | Xs]).

And it's direct and tail-recursive… all at once.

@mareknowak
Copy link
Author

Cool! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment