Instantly share code, notes, and snippets.

@ggb ggb/assignment1.erl
Created Feb 27, 2017

Embed
What would you like to do?
Functional Programming in Erlang - First Assignment
-module(assignment1).
-export([bits/1, area/1, perimeter/1, enclose/1, bits_rec/1]).
% Shapes
% How the shapes are defined:
% circle: {circle, {x, y}, r}
% rectangle: {rectangle, {x1, y1},{x2, y2}}
% triangle: {triangle, {x1, y1}, A, B, C}
area({circle, {_X, _Y}, R}) ->
math:pi() * R * R;
area({rectangle, {X1, Y1},{X2, Y2}}) ->
(X2 - X1) * (Y2 - Y1);
area({triangle, _P, A, B, C}) ->
S = (A + B + C) / 2,
math:sqrt(S * (S - A) * (S - B) * (S - C)).
perimeter({circle, {_X, _Y}, R}) ->
2 * math:pi() * R;
perimeter({rectangle, {X1, Y1}, {X2, Y2}}) ->
2 * (X2 - X1) + 2 * (Y2 * Y1);
perimeter({triangle, _P, A, B, C}) ->
A + B + C.
enclose({circle, {X, Y}, R}) ->
{rectangle, {X - R, Y - R}, {X + R, Y + R}};
enclose({rectangle, P1, P2}) ->
{rectangle, P1, P2};
enclose({triangle, {X, Y}, A, B, C}) ->
Area = area({triangle, {X, Y}, A, B, C}),
Base = max(max(A, B), max(B, C)),
Height = (Area * 2) / Base,
{rectangle, {X, Y}, {X + Base, Y + Height}}.
% Summing the bits
bits_rec(0) ->
0;
bits_rec(N) ->
(N rem 2) + bits_rec(N div 2).
% Better (because faster) tail-recursive variant
bits(0, M) ->
M;
bits(N, M) ->
bits(N div 2, M + N rem 2).
bits(N) ->
bits(N, 0).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment