Advertisement
Guest User

Assignment 1 of Functional Programming in Erlang

a guest
May 28th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.71 KB | None | 0 0
  1. -module(assignment).
  2. -export([dr_bits/1, bits/1, bits/2, perimeter/1, area/1, enclose/1]).
  3.  
  4. % Shapes
  5. % Define a function perimeter/1 which takes a shape and
  6. % returns the perimeter of the shape.
  7. % Choose a suitable representation of triangles,
  8. % and augment area/1 and perimeter/1 to handle this case too.
  9. % Define a function enclose/1 that takes a shape and returns the
  10. % smallest enclosing rectangle of the shape.
  11. perimeter({circle, {_,_}, R}) -> 2*math:pi()*R;
  12. perimeter({triangle, {_,_}, E1, E2, E3}) -> E1 + E2 + E3;
  13. perimeter({rectangle,{_,_}, Base, Height}) -> Base * 2 + Height * 2.
  14.  
  15. area({circle, {_,_}, R}) -> math:pi()*R*R;
  16. area({triangle, {_,_}, E1, E2, E3}) ->
  17.     P = (E1 + E2 + E3) / 2,
  18.     math:sqrt(P*(P-E1)*(P-E2)*(P-E3));
  19. area({rectangle,{_,_}, Base, Height}) -> Base * Height.
  20.  
  21. enclose({circle, {X,Y}, R}) -> {rectangle,{X,Y}, R, R};
  22. enclose({triangle, {X,Y}, E1, E2, E3}) ->
  23.     Base = E1, % take a side as a base,
  24.     Height = 2 * area({triangle, {X,Y}, E1, E2, E3}) / Base,
  25.     {rectangle, {Base/2, Height/2}, Base, Height};
  26. enclose({rectangle,{X,Y}, Base, Height}) -> {rectangle,{X,Y}, Base, Height}.
  27.  
  28. % Bits
  29. % Define a function bits/1 that takes a positive integer N and
  30. % returns the sum of the bits in the binary representation.
  31. % For example bits(7) is 3 and bits(8) is 1.
  32. % See whether you can make both a direct recursive and a tail recursive definition.
  33.  
  34. % Direct recursive bit implementation
  35. dr_bits(N) when N =< 0 ->
  36.     "";
  37. dr_bits(N) when N > 0 ->
  38.     dr_bits(N div 2) ++ integer_to_list(N rem 2).
  39.  
  40. % Tail recursive bit implementation
  41. bits(N, Acc) when N =< 0 ->
  42.     Acc;
  43. bits(N, Acc) when N > 0 ->
  44.     bits(N div 2, integer_to_list(N rem 2) ++ Acc).
  45.  
  46. bits(N) -> bits(N, "").
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement