Skip to content

Instantly share code, notes, and snippets.

@stormwatch
Created May 16, 2020 20:02
Show Gist options
  • Save stormwatch/425401474f95d3a6d56b277359115e35 to your computer and use it in GitHub Desktop.
Save stormwatch/425401474f95d3a6d56b277359115e35 to your computer and use it in GitHub Desktop.
-module(one15).
-export([xOr1/2, xOr2/2, xOr3/2, xOr4/2, xOr5/2, xOr6/2, xOr7/2, maxThree/3, howManyEqual/3, howManyEqual2/3, howManyEqual3/3]).
%% first example given by Prof. Thompson
xOr1(true, false) ->
true;
xOr1(false, true) ->
true;
xOr1(_,_) ->
false.
% second example given by Prof. Thompson
xOr2(X, X) ->
false;
xOr2(_, _) ->
true.
% Give at least three other examples:
xOr3(X, Y) ->
X =/= Y.
xOr4(X, Y) ->
not(X == Y).
xOr5(true, Y) ->
not(Y);
xOr5(false, Y) ->
Y.
xOr6(X, Y) ->
X and not(Y) or Y and not(X).
xOr7(X, false) ->
X;
xOr7(false, Y) ->
Y.
%% Maximum of three
%% Give a definition of the function maxThree which takes three integers and
%% returns the maximum of the three. You can use the max function, which gives
%% the maximum of two numbers, in writing your definition.
%% maxThree(34,25,36) = 36
maxThree(X, Y, Z) ->
max(max(X, Y), Z).
%% Give a definition of the function howManyEqual which takes three integers and
%% returns an integer, counting how many of its three arguments are equal, so
%% that:
%% howManyEqual(34,25,36) = 0
%% howManyEqual(34,25,34) = 2
%% howManyEqual(34,34,34) = 3
%% This implementation will fail while comparing ints and floats
howManyEqual(X, X, X) ->
3;
howManyEqual(X, X, _) ->
2;
howManyEqual(X, _, X) ->
2;
howManyEqual(_, X, X) ->
2;
howManyEqual(_, _, _) ->
0.
%% one approach is using guards
howManyEqual2(X, Y, Z) when (X == Y) and (Y == Z) ->
3;
howManyEqual2(X, Y, Z) when (X == Y) or (X == Z) or (Y == Z)->
2;
howManyEqual2(_, _, _) ->
0.
%% another approach could be to explicitely force the conversion of the
%% arguments to float prior to calling howManyEqual
howManyEqual3(X, Y, Z) ->
howManyEqual(float(X), float(Y), float(Z)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment