Advertisement
Guest User

excessive_1_24.erl

a guest
Mar 2nd, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.75 KB | None | 0 0
  1. %%
  2. % Student: Cristian David Grajales
  3. %%
  4.  
  5. -module(exercise).
  6. -export([perimeter/1, area/1, enclose/1, bits/1]).
  7.  
  8. %%
  9. % I choose, square, circle, and triangle becase they are the most basic figures. since the
  10. % porpouse of the excercise is to practice pattern matching I guess it is enough.
  11. % To represent the figures I choose to use the side lenghts, I am no using the coordinates but the side length of the sides.
  12. %%
  13.  
  14. %%
  15. % Perimeter
  16. %%
  17. perimeter({square, X}) ->
  18.     X*4;
  19. perimeter({rectangle, X, Y}) ->
  20.     2*(X+Y);
  21. perimeter({circle, R}) ->
  22.     2*R*math:pi();
  23. % This is a triangle rectangle
  24. perimeter({triangle,X,Y}) ->
  25.     X+Y+hypotenuse(X,Y);
  26. perimeter(_) ->
  27.     {error, <<"figure not supported">>}.
  28.  
  29. %%
  30. % Area
  31. %%
  32. area({square, X}) ->
  33.     X*X;
  34. area({rectangle, X, Y}) ->
  35.     X*Y;
  36. area({circle, R}) ->
  37.     math:pi()*R*R;
  38.     % This is a triangle rectangle
  39. area({triangle, X, Y}) ->
  40.     H = hypotenuse(X,Y),
  41.     P = perimeter({triangle, X, Y})/2,
  42.     math:sqrt( P * ( P - X ) * ( P - Y ) * ( P - H ) );
  43. area(_) ->
  44.     {error, <<"figure not supported">>}.
  45.  
  46. %%
  47. % Enclose
  48. % Returns the lenght of the sides of the smallest rectangle that encloses the figure
  49. %%
  50. enclose({square, X}) ->
  51.     {X, X};
  52. enclose({rectangle, X, Y}) ->
  53.     {X, Y};
  54. enclose({circle, R}) ->
  55.     D = 2*R,
  56.     {D, D};
  57. % Given that this is a triangle rectangle the  smallest encolsing rectange will be
  58. enclose({triangle, A, B}) ->
  59.     {A, B};
  60. enclose(_) ->
  61.     {error, <<"figure not supported">>}.
  62.  
  63. %%
  64. % Bits
  65. %%
  66. bitsp(0, X) ->
  67.     X;
  68. bitsp(1, X) ->
  69.     X+1;
  70. bitsp(N, X) when N > 0 ->
  71.     bitsp( N div 2, X + ( N rem 2 ) ).
  72. bits(N) ->
  73.     bitsp(N, 0).
  74.  
  75. %%
  76. % PRIVATE FUNCTIONS
  77. %%
  78. hypotenuse(X,Y) ->
  79.     math:sqrt( first:square(X) + first:square(Y*Y) ).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement