Last active
February 26, 2017 21:50
-
-
Save fxn/05b4be6730f60289ee314b184cd9d6ba to your computer and use it in GitHub Desktop.
Exercise 1.24 of the course "Functional Programming in Erlang", by Simon Thompson
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -module(ex). | |
| -export([perimeter/1, area/1, enclose/1, bitsR/1, bitsTR/1]). | |
| % Shapes are represented with these tuples: | |
| % | |
| % {circle, {X, Y}, R} | |
| % {rectangle, {X, Y}, H, W} | |
| % {triangle, {X, Y}, A, B, C} | |
| % | |
| % These tuples are not able to express the orientation of the rectangles and | |
| % triangles, but that is in line with the lesson that showcases area/1. | |
| perimeter({circle, _, R}) -> | |
| 2*math:pi()*R; | |
| perimeter({rectangle, _, H, W}) -> | |
| 2*(H + W); | |
| perimeter({triangle, _, A, B, C}) -> | |
| A + B + C. | |
| area({circle, _, R}) -> | |
| math:pi()*R*R; | |
| area({rectangle, _, H, W}) -> | |
| H*W; | |
| % This is called Heron's formula, yields the area given the sides. | |
| area({triangle, _, A, B, C}) -> | |
| S = (A + B + C)/2, | |
| math:sqrt(S*(S - A)*(S - B)*(S - C)). | |
| % A circle is minimally enclosed in a square whose side is the circle diameter. | |
| enclose({circle, C, R}) -> | |
| Diameter = 2*R, | |
| {rectangle, C, Diameter, Diameter}; | |
| % A rectangle is minimally enclosed in itself. | |
| enclose({rectangle, C, H, W}) -> | |
| {rectangle, C, H, W}; | |
| % The smallest rectangle enclosing a triangle has the largest side as its base | |
| % and the triangle altitude corresponding to that side as its height. Since | |
| % area = b*h/2, we can leverage the area function. | |
| enclose({triangle, Center, A, B, C}) -> | |
| Base = lists:max([A, B, C]), | |
| Height = 2*area({triangle, Center, A, B, C})/Base, | |
| {rectangle, Center, Base, Height}. | |
| bitsR(0) -> | |
| 0; | |
| bitsR(N) -> | |
| bitsR(N div 2) + N rem 2. | |
| bitsTR(N) -> | |
| bitsTR(N, 0). | |
| bitsTR(0, S) -> | |
| S; | |
| bitsTR(N, S) -> | |
| bitsTR(N div 2, S + (N rem 2)). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment