Advertisement
Guest User

Untitled

a guest
Feb 26th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. -module(assignment1).
  2. -export([perimeter/1, area/1, enclose/1, bits/1, directBits/1]).
  3.  
  4. %%%ASSIGNEMENT ABOUT perimeter, area and enclose functions
  5.  
  6. perimeter({'circle', {_X,_Y}, R}) -> (R+R)*math:pi();
  7. perimeter({'rectangle', {_X,_Y}, H,W}) -> (H+W)*2;
  8. perimeter({'triangle', {_X,_Y}, A,B,C}) -> A+B+C.
  9.  
  10. area({'circle', {_X,_Y}, R}) -> (R*R)*math:pi();
  11. area({'rectangle', {_X,_Y}, H,W}) -> (H*W);
  12. area({'triangle', {_X,_Y}, A,B,C}) -> triangleArea(A,B,C).
  13.  
  14. enclose({'circle', {X,Y}, R}) -> {'rectangle', {X,Y}, R*2,R*2};
  15. enclose({'rectangle', {X,Y}, H,W}) -> {'rectangle', {X,Y}, H,W};
  16. enclose(Triangle={'triangle', {X,Y}, A,B,C}) ->
  17. MaxSide = max(max(A,B),C),
  18. TriangleHeight = 2*area(Triangle)/MaxSide, %retrieving triangle height
  19. {'rectangle', {X,Y}, MaxSide,TriangleHeight}.
  20.  
  21.  
  22. %Heron's formula to calculate triangle area
  23. triangleArea(A,B,C) ->
  24. S = (A+B+C)/2,
  25. math:sqrt(S*(S-A)*(S-B)*(S-C)).
  26.  
  27.  
  28. %%%HERE COMES THE ASSIGNMENT ABOUT BITS%%%
  29.  
  30. %this is the exposed function
  31. bits(NUMBER) ->
  32. %first, transform the input number to a boolean value, then invoke the recursive function
  33. recursiveBits(integer_to_list(NUMBER,2), 0).
  34.  
  35. %%%TAIL RECURSIVE FUNCTION%%%
  36. %%%It works as follow:
  37. %%%unit case: if the list in input is empty, returns the accumulated value of bits
  38. %%%when the list is not empty and its head value is '1' bit, call the recursive function increasing the number of bits
  39. %%%otherwise call the recursive function over the tail of the list.
  40. recursiveBits([], BITS) -> BITS;
  41. recursiveBits(LIST, BITS) when hd(LIST) == 49 -> recursiveBits(tl(LIST),BITS+1);
  42. recursiveBits(LIST, BITS) -> recursiveBits(tl(LIST),BITS).
  43.  
  44.  
  45. directBits(NUMBER) ->
  46. N = integer_to_list(NUMBER,2),
  47. directRecursiveBits(N).
  48.  
  49.  
  50. %%%DIRECT RECURSIVE BITS%%%
  51. %%%It is a recursion function that does not use any accumulator.
  52. %%%Maybe in this exercise the drawback in using a direct recursive approach are not so big because of
  53. %%&the generally small size of the list to iterate on.
  54. directRecursiveBits([]) -> 0;
  55. directRecursiveBits(LIST) when (length(LIST) == 1) and (hd(LIST) == 49) -> 1;
  56. directRecursiveBits(LIST) when hd(LIST) == 49 -> 1 + directRecursiveBits(tl(LIST));
  57. directRecursiveBits(LIST) -> directRecursiveBits(tl(LIST)).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement