Skip to content

Instantly share code, notes, and snippets.

@shakerlxxv
Last active March 2, 2017 10:00
Show Gist options
  • Save shakerlxxv/c4ce9ba760c68582da8c98b19b410cf1 to your computer and use it in GitHub Desktop.
Save shakerlxxv/c4ce9ba760c68582da8c98b19b410cf1 to your computer and use it in GitHub Desktop.
FUNCTIONAL PROGRAMMING IN ERLANG THE UNIVERSITY OF KENT: Variables and patterns in practice
-module(patterns).
-include_lib("eunit/include/eunit.hrl").
-export([xOr1/2,xOr2/2,xOr3/2,maxThree/3,howManyEqual/3]).
xOr1(A,B) ->
(not (A and B)) and (A == not B).
% the first clause is necessary to ensure the function errors
% if given a non-boolean argument.
xOr1_test() ->
false = xOr1(true,true),
true = xOr1(true,false),
false = xOr1(false,false),
true = xOr1(false,true).
xOr2(A,B) ->
(not (A and B)) and (A =/= B).
xOr2_test() ->
false = xOr2(true,true),
true = xOr2(true,false),
false = xOr2(false,false),
true = xOr2(false,true).
xOr3(A,B) ->
(A and not B) or (B and not A).
xOr3_test() ->
false = xOr3(true,true),
true = xOr3(true,false),
false = xOr3(false,false),
true = xOr3(false,true).
maxThree(A,B,C) ->
max(A,max(B,C)).
maxThree_test() ->
1 = maxThree(0,1,-1),
9 = maxThree(3,6,9),
7 = maxThree(7,6,5).
howManyEqual(A,A,A) ->
3;
howManyEqual(A,A,_) ->
2;
howManyEqual(A,_,A) ->
2;
howManyEqual(_,A,A) ->
2;
howManyEqual(_,_,_) ->
0.
howManyEqual_test() ->
3 = howManyEqual(1,1,1),
2 = howManyEqual(1,0,1),
2 = howManyEqual(0,1,1),
0 = howManyEqual(0,1,2).
@ehyland
Copy link

ehyland commented Mar 2, 2017

Thanks for the introduction to erlang unit tests!

You could reduce the xOrN_test functions by creating a test helper function

-module(patterns).
-include_lib("eunit/include/eunit.hrl").
-export([xOr1/2,xOr2/2,xOr3/2,maxThree/3,howManyEqual/3]).

testXOr(FN) ->
    false = FN(true,true),
    true  = FN(true,false),
    false = FN(false,false),
    true  = FN(false,true).

xOr1(A,B) ->
    (not (A and B)) and (A == not B).

xOr1_test() ->
    testXOr(fun xOr1/2).

xOr2(A,B) ->
    (not (A and B)) and (A =/= B).

xOr2_test() ->
    testXOr(fun xOr2/2).

xOr3(A,B) ->
    (A and not B) or (B and not A).

xOr3_test() ->
    testXOr(fun xOr3/2).

maxThree(A,B,C) ->
    max(A,max(B,C)).

maxThree_test() ->
    1 = maxThree(0,1,-1),
    9 = maxThree(3,6,9),
    7 = maxThree(7,6,5).

howManyEqual(A,A,A) ->
    3;
howManyEqual(A,A,_) ->
    2;
howManyEqual(A,_,A) ->
    2;
howManyEqual(_,A,A) ->
    2;
howManyEqual(_,_,_) ->
    0.

howManyEqual_test() ->
    3 = howManyEqual(1,1,1),
    2 = howManyEqual(1,0,1),
    2 = howManyEqual(0,1,1),
    0 = howManyEqual(0,1,2).

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