Skip to content

Instantly share code, notes, and snippets.

@ubaldop
Last active February 26, 2017 16:55
Show Gist options
  • Save ubaldop/19c2a97ada0f2e65df125c02df351229 to your computer and use it in GitHub Desktop.
Save ubaldop/19c2a97ada0f2e65df125c02df351229 to your computer and use it in GitHub Desktop.
Functional Programming with Erlang - Assignment 1
-module(assignment1).
-export([perimeter/1, area/1, enclose/1, bits/1, directBits/1]).
%%%ASSIGNEMENT ABOUT perimeter, area and enclose functions
perimeter({'circle', {_X,_Y}, R}) -> (R+R)*math:pi();
perimeter({'rectangle', {_X,_Y}, H,W}) -> (H+W)*2;
perimeter({'triangle', {_X,_Y}, A,B,C}) -> A+B+C.
area({'circle', {_X,_Y}, R}) -> (R*R)*math:pi();
area({'rectangle', {_X,_Y}, H,W}) -> (H*W);
area({'triangle', {_X,_Y}, A,B,C}) -> triangleArea(A,B,C).
enclose({'circle', {X,Y}, R}) -> {'rectangle', {X,Y}, R*2,R*2};
enclose({'rectangle', {X,Y}, H,W}) -> {'rectangle', {X,Y}, H,W};
enclose(Triangle={'triangle', {X,Y}, A,B,C}) ->
MaxSide = max(max(A,B),C),
TriangleHeight = 2*area(Triangle)/MaxSide, %retrieving triangle height
{'rectangle', {X,Y}, MaxSide,TriangleHeight}.
%Heron's formula to calculate triangle area
triangleArea(A,B,C) ->
S = (A+B+C)/2,
math:sqrt(S*(S-A)*(S-B)*(S-C)).
%%%HERE COMES THE ASSIGNMENT ABOUT BITS%%%
%this is the exposed function
bits(NUMBER) ->
%first, transform the input number to a boolean value, then invoke the recursive function
recursiveBits(integer_to_list(NUMBER,2), 0).
%%%TAIL RECURSIVE FUNCTION%%%
%%%It works as follow:
%%%unit case: if the list in input is empty, returns the accumulated value of bits
%%%when the list is not empty and its head value is '1' bit, call the recursive function increasing the number of bits
%%%otherwise call the recursive function over the tail of the list.
recursiveBits([], BITS) -> BITS;
recursiveBits(LIST, BITS) when hd(LIST) == 49 -> recursiveBits(tl(LIST),BITS+1);
recursiveBits(LIST, BITS) -> recursiveBits(tl(LIST),BITS).
directBits(NUMBER) ->
N = integer_to_list(NUMBER,2),
directRecursiveBits(N).
%%%DIRECT RECURSIVE BITS%%%
%%%It is a recursion function that does not use any accumulator.
%%%Maybe in this exercise the drawback in using a direct recursive approach are not so big because of
%%&the generally small size of the list to iterate on.
directRecursiveBits([]) -> 0;
directRecursiveBits(LIST) when (length(LIST) == 1) and (hd(LIST) == 49) -> 1;
directRecursiveBits(LIST) when hd(LIST) == 49 -> 1 + directRecursiveBits(tl(LIST));
directRecursiveBits(LIST) -> directRecursiveBits(tl(LIST)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment