Skip to content

Instantly share code, notes, and snippets.

@mwpastore
Created March 4, 2017 00:29
Show Gist options
  • Save mwpastore/6c48c8e8ebaead0532226e833dd4575b to your computer and use it in GitHub Desktop.
Save mwpastore/6c48c8e8ebaead0532226e833dd4575b to your computer and use it in GitHub Desktop.
FutureLearn — Functional Programming in Erlang — Week 1
-module(mwpastore_week1).
-export([area/1, perimeter/1, enclose/1, bits/1]).
area({square, L}) ->
L * L;
area({rectangle, H, W}) ->
H * W;
area({circle, R}) ->
math:pi() * R * R;
area({triangle, A, B, C}) ->
S = (A + B + C) / 2,
math:sqrt(S * (S - A) * (S - B) * (S - C)).
perimeter({square, L}) ->
4 * L;
perimeter({rectangle, H, W}) ->
2 * H + 2 * W;
perimeter({circle, R}) ->
2 * math:pi() * R;
perimeter({triangle, A, B, C}) ->
A + B + C.
enclose({square, L}) ->
{rectangle, L, L};
enclose({rectangle, H, W}) ->
{rectangle, H, W};
enclose({circle, R}) ->
{rectangle, 2 * R, 2 * R};
enclose({triangle, A, B, C}) ->
W = max(A, max(B, C)), % take the longest side as the base of the triangle
H = 2 * area({triangle, A, B, C}) / W, % find the height using the area
{rectangle, H, W}.
bits(N) when N >= 0 ->
bits(N, 0);
bits(N) ->
bits(-N, 1). % count the sign bit :)
% Brian Kernighan's algorithm
bits(0, C) -> C;
bits(N, C) ->
bits(N band (N - 1), C + 1).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment