Last active
May 7, 2020 08:23
-
-
Save mareknowak/37ed8fed4104d4e3f016a47b098ecf9b to your computer and use it in GitHub Desktop.
Practice patterns (1.15)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%% @doc Practice patterns (1.15) | |
-module(patterns). | |
-export([x_or_1/2, x_or_2/2, x_or_3/2, max/2, max_three/3, how_many_equal/3, test/0]). | |
%% @doc Give three "exclusive ors" | |
x_or_1(X, Y) -> | |
X =/= Y. | |
test_x_or_1() -> | |
true = patterns:x_or_1(true, false), | |
true = patterns:x_or_1(false, true), | |
false = patterns:x_or_1(false, false), | |
false = patterns:x_or_1(true, true), | |
ok. | |
x_or_2(X, Y) -> | |
not X == Y. | |
test_x_or_2() -> | |
true = patterns:x_or_2(true, false), | |
true = patterns:x_or_2(false, true), | |
false = patterns:x_or_2(false, false), | |
false = patterns:x_or_2(true, true), | |
ok. | |
x_or_3(X, Y) -> | |
X_and_NY = X and (not Y), | |
Y_and_NX = Y and (not X), | |
X_and_NY or Y_and_NX. | |
test_x_or_3() -> | |
true = patterns:x_or_3(true, false), | |
true = patterns:x_or_3(false, true), | |
false = patterns:x_or_3(false, false), | |
false = patterns:x_or_3(true, true), | |
ok. | |
select(true, X, _) -> X; | |
select(false, _, Y) -> Y. | |
%% @doc Give maximum of two numbers | |
max(X, Y) -> | |
First_wins = X > Y, | |
select(First_wins, X, Y). | |
test_max() -> | |
A = 2, | |
B = 3, | |
C = 20, | |
B = patterns:max(A, B), | |
C = patterns:max(C, B), | |
ok. | |
%% @doc Give maximum of three numbers | |
max_three(X, Y, Z) -> | |
A = patterns:max(X, Y), | |
patterns:max(A, Z). | |
test_max_three() -> | |
36 = patterns:max_three(34, 25, 36), | |
100 = patterns:max_three(100, 25, 36), | |
ok. | |
%% @doc Count how many of three arguments are equal | |
how_many_equal(X, X, X) -> | |
3; | |
how_many_equal(X, X, _) -> | |
2; | |
how_many_equal(X, _, X) -> | |
2; | |
how_many_equal(_, X, X) -> | |
2; | |
how_many_equal(_, _, _) -> | |
0. | |
test_how_many_equal() -> | |
A = 34, | |
B = 35, | |
C = 36, | |
0 = patterns:how_many_equal(A, B, C), | |
2 = patterns:how_many_equal(A, A, B), | |
3 = patterns:how_many_equal(A, A, A), | |
ok. | |
%% @doc test functions: x_ors, max, max_three, and how_many_equal | |
test() -> | |
ok = test_x_or_1(), | |
ok = test_x_or_2(), | |
ok = test_x_or_3(), | |
ok = test_max(), | |
ok = test_max_three(), | |
ok = test_how_many_equal(), | |
ok. |
Thanks for kind words and very informative comments on idiomatic Erlang during the course.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome!!