Skip to content

Instantly share code, notes, and snippets.

@gupta82anish
Last active May 13, 2020 08:51
Show Gist options
  • Save gupta82anish/06507e3b61569ed69a687de8f9f8b23a to your computer and use it in GitHub Desktop.
Save gupta82anish/06507e3b61569ed69a687de8f9f8b23a to your computer and use it in GitHub Desktop.
Practice Assignment for Future Learn Functional Programming with Erlang Course.
-module(assignment).
-export([perimeter/1,area/1,bits/1,tests/0]).
%Perimeter functions for circle,rectangle, square
perimeter({circle, {_X,_Y}, R}) ->
2*math:pi()*R;
perimeter({rectangle,H,W}) ->
2*H + 2*W;
perimeter({square,L}) ->
math:pow(L,2);
%Perimeter of right triangle and triangle
perimeter({right_triangle,A,B}) ->
A + B + math:sqrt(math:pow(A,2) + math:pow(B,2)); %calculating the hypotenuse
perimeter({triangle,A,B,C}) ->
case is_valid(A,B,C) of %check if triangle is valid
false ->
io:format("Invalid Triangle");
true ->
A+B+C
end.
% Area of right triangle and simple triangle
area({right_triangle,A,B}) ->
A*B/2;
area({triangle,A,B,C}) ->
case is_valid(A,B,C) of %check if triangle is valid
false ->
io:format("Invalid Triangle");
true ->
S = (A+B+C)/2,
math:sqrt(S*(S-A)*(S-B)*(S-C))
end.
%function to check validity of triangle
is_valid(A,B,C) when A+B>C, B+C>A, C+A>B ->
true;
is_valid(_A,_B,_C) ->
false.
% Tail recursive definition for converting to binary
convert_to_binary(0,List) ->
List;
convert_to_binary(N,List) when N>0 ->
R = N rem 2,
convert_to_binary(N div 2,[R|List]).
convert_to_binary(N) ->
convert_to_binary(N, []).
% using the sum function of lists module to sum the integers in the list
bits(N) ->
lists:sum(convert_to_binary(N)).
test_bits() ->
2 = bits(3),
3 = bits(7),
1 = bits(8),
pass.
test_perimeter() ->
31.41592653589793 = perimeter({circle, {0,0}, 5}),
22 = perimeter({rectangle,6,5}),
25.0 = perimeter({square, 5}),
12.0 = perimeter({right_triangle, 3,4}),
12 = perimeter({triangle,3,4,5}),
pass.
test_area() ->
6.0 = area({right_triangle,3,4}),
6.0 = area({triangle,3,4,5}),
pass.
tests() ->
pass = test_perimeter(),
pass = test_area(),
pass = test_bits(),
pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment