Skip to content

Instantly share code, notes, and snippets.

@andreburgaud
Last active June 23, 2017 05:16
Show Gist options
  • Save andreburgaud/c8baaddfb832c78a049733f70af56397 to your computer and use it in GitHub Desktop.
Save andreburgaud/c8baaddfb832c78a049733f70af56397 to your computer and use it in GitHub Desktop.
FutureLearn - Functional Programming in Erlang 1.9
-module(first).
-export([double/1,treble/1,square/1,mult/2,area/3]).
mult(X, Y) ->
X*Y.
double(X) ->
mult(2, X).
% Area of a triangle (Heron's formula)
area(A,B,C) ->
S = (A+B+C)/2,
math:sqrt(S*(S-A)*(S-B)*(S-C)).
square(X) ->
mult(X, X).
treble(X) ->
mult(3, X).
-module(second).
-export([area/2,area_heron/2,hypotenuse/2,perimeter/2]).
% C = sqrt(A*A+B*B)
hypotenuse(A, B) ->
math:sqrt(first:square(A)+first:square(B)).
% P = A+B+C (C=hypotenuse)
perimeter(A, B) ->
A+B+hypotenuse(A,B).
% First option:
% Right triangle => you can use fromula A = 1/2BH
% Where A = area, B = base and H = height
area(A, B) ->
first:mult(1/2,first:mult(A,B)).
% Second option:
% Use heron's formula from module first
area_heron(A, B) ->
C = hypotenuse(A, B),
first:area(A, B, C).
-module(test).
-include_lib("eunit/include/eunit.hrl").
% To run tests in Erlang shell:
% c(test).
% eunit:test(test).
second_test_() ->
[?_assert(second:area(3,4) =:= second:area_heron(3,4)),
?_assert(second:perimeter(3,4) =:= 12.0),
?_assert(second:hypotenuse(3,4) =:= 5.0)].
first_test_() ->
[?_assert(first:double(4) =:= 8),
?_assert(first:treble(4) =:= 12),
?_assert(first:square(4) =:= 16),
?_assert(first:mult(3,4) =:= 12),
?_assert(first:area(3,4,5) =:= 6.0)].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment