Skip to content

Instantly share code, notes, and snippets.

@tgallant
Last active February 26, 2017 20:42
Show Gist options
  • Save tgallant/e95d8bba2f35458d4431acd90397df2d to your computer and use it in GitHub Desktop.
Save tgallant/e95d8bba2f35458d4431acd90397df2d to your computer and use it in GitHub Desktop.
-module(pm).
-export([perimiter/1,area/1,enclosure/1,linearBits/1,bits/1]).
%% Shape objects:
%%
%% For the sake of brevity, all shape values
%% are expected to be positive integers.
%%
%% {circle, Radius}
%% {rectangle, {Width,Height}}
%% {triangle, {Len1,Len2,Len3}}
%% {triangle, {Base,Height}}
perimiter({circle, R}) ->
math:pi() * 2*R;
perimiter({rectangle, {W, H}}) ->
2*W + 2*H;
perimiter({triangle, {A,B,C}}) ->
A+B+C.
area({triangle, {B,H}}) -> (B*H)/2.
%% All return values assume the same center point as
%% the input object
enclosure({circle, R}) ->
{rectangle, {R,R}};
enclosure({rectangle, {W,H}}) ->
{rectangle, {W,H}};
enclosure({triangle, {B,H}}) ->
{rectangle, {B,H}}.
%%
%% bits() Linear Recursion
%%
linearBits(N) when N > 0 ->
N rem 2 + bits(N div 2).
%%
%% bits() Iterative/Tail Recursion
%%
%% bits(Number)
bits(N) -> bits(N,0).
%% bits(Number,Sum)
bits(0,S) -> S;
bits(N,S) -> bits(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