Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(assignment).
- -export([dr_bits/1, bits/1, bits/2, perimeter/1, area/1, enclose/1]).
- % Shapes
- % Define a function perimeter/1 which takes a shape and
- % returns the perimeter of the shape.
- % Choose a suitable representation of triangles,
- % and augment area/1 and perimeter/1 to handle this case too.
- % Define a function enclose/1 that takes a shape and returns the
- % smallest enclosing rectangle of the shape.
- perimeter({circle, {_,_}, R}) -> 2*math:pi()*R;
- perimeter({triangle, {_,_}, E1, E2, E3}) -> E1 + E2 + E3;
- perimeter({rectangle,{_,_}, Base, Height}) -> Base * 2 + Height * 2.
- area({circle, {_,_}, R}) -> math:pi()*R*R;
- area({triangle, {_,_}, E1, E2, E3}) ->
- P = (E1 + E2 + E3) / 2,
- math:sqrt(P*(P-E1)*(P-E2)*(P-E3));
- area({rectangle,{_,_}, Base, Height}) -> Base * Height.
- enclose({circle, {X,Y}, R}) -> {rectangle,{X,Y}, R, R};
- enclose({triangle, {X,Y}, E1, E2, E3}) ->
- Base = E1, % take a side as a base,
- Height = 2 * area({triangle, {X,Y}, E1, E2, E3}) / Base,
- {rectangle, {Base/2, Height/2}, Base, Height};
- enclose({rectangle,{X,Y}, Base, Height}) -> {rectangle,{X,Y}, Base, Height}.
- % Bits
- % Define a function bits/1 that takes a positive integer N and
- % returns the sum of the bits in the binary representation.
- % For example bits(7) is 3 and bits(8) is 1.
- % See whether you can make both a direct recursive and a tail recursive definition.
- % Direct recursive bit implementation
- dr_bits(N) when N =< 0 ->
- "";
- dr_bits(N) when N > 0 ->
- dr_bits(N div 2) ++ integer_to_list(N rem 2).
- % Tail recursive bit implementation
- bits(N, Acc) when N =< 0 ->
- Acc;
- bits(N, Acc) when N > 0 ->
- bits(N div 2, integer_to_list(N rem 2) ++ Acc).
- bits(N) -> bits(N, "").
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement