Skip to content

Instantly share code, notes, and snippets.

@andreburgaud
Last active June 25, 2017 16:19
Show Gist options
  • Save andreburgaud/3ebd87067b8c268bf75b23ef7d62d232 to your computer and use it in GitHub Desktop.
Save andreburgaud/3ebd87067b8c268bf75b23ef7d62d232 to your computer and use it in GitHub Desktop.
FutureLearn - Functional Programming in Erlang 1.15 - Erlang pattern matching examples with hand-crafted tests
-module(patterns).
-export([all_tests/0]).
% all_tests invokes all tests (xor, maxThree, howManyEquals)
all_tests() ->
all_xor_tests(),
test_max_three(),
test_how_many().
% all_xor_tests invokes all XOR tests.
all_xor_tests() ->
io:format("Testing xor functions...~n"),
F = fun(true) ->
io:format("success~n");
(false) ->
io:format("error~n")
end,
lists:foreach(
F,
[test_xor(fun xOr/2),
test_xor(fun xOr1/2),
test_xor(fun xOr2/2),
test_xor(fun xOr3/2),
test_xor(fun xOr4/2)]).
% Common test function taking an xor function as parameter
test_xor(XOR) ->
F = fun({A, B, C}) -> XOR(A, B) == C end,
lists:all(F, [{true, false, true}, {false, true, true}, {true, true, false}, {false, false, false}]).
% First example in the video.
xOr(true, false) ->
true;
xOr(false, true) ->
true;
xOr(_, _) ->
false.
% Second example in the video.
xOr1(X, X) ->
false;
xOr1(_, _) ->
true.
% Exclusive or new example 1
xOr2(true, true) ->
false;
xOr2(false, false) ->
false;
xOr2(_, _) ->
true.
% Exclusive or new example 2
xOr3(X, true) ->
X =/= true;
xOr3(X, false) ->
X =/= false.
% Exclusive or new example 3
xOr4(X, true) when X == true ->
false;
xOr4(X, false) when X == false ->
false;
xOr4(_, _) ->
true.
% Helper function for testing maxThree and howManyEqual.
result(true) ->
io:format("success~n");
result(false) ->
io:format("error~n").
% maxThree return the maximum value passed of 3 parameters.
maxThree(X, Y, Z) ->
max(X, max(Y, Z)).
% test_max_three validates maxThree function samples.
test_max_three() ->
io:format("Testing max three...~n"),
result(lists:all(fun(X) -> X == true end,
[maxThree(1,2,3)=:=3,
maxThree(100,2,3)=:=100,
maxThree(0,0,0)=:=0])).
% howManyEqual return the number of equal values among the 3 paramters.
howManyEqual(X, X, X) -> 3;
howManyEqual(X, X, _) -> 2;
howManyEqual(_, X, X) -> 2;
howManyEqual(X, _, X) -> 2;
howManyEqual(_, _, _) -> 0.
% test_max_three validates howManyEqual function samples.
test_how_many() ->
io:format("Testing how many equals...~n"),
result(lists:all(fun(X) -> X == true end,
[howManyEqual(1,2,3)=:=0,
howManyEqual(100,2,100)=:=2,
howManyEqual(0,0,0)=:=3])).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment