Instantly share code, notes, and snippets.

# rhnonose/first.erl

Last active February 22, 2017 17:56
Show Gist options
• Save rhnonose/8501a3fd60e498310445b50750269dbd to your computer and use it in GitHub Desktop.
FutureLearn exercises
This file contains 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(first). -export([double/1, mult/2, area/3, square/1, treble/1]). mult(X,Y) -> X*Y. double(X) -> mult(X, 2). area(A,B,C) -> S = (A+B+C)/2, math:sqrt(S*(S-A)*(S-B)*(S-C)). square(A) -> math:sqrt(A). treble(A) -> A*3.
This file contains 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(recur). -export([fac/1, fib/1, pieces/1]). % Factorial fac(0) -> 1; fac(N) when N > 0 -> N*fac(N-1); fac(_) -> 1. % Fibonnacci fib(0) -> 0; fib(1) -> 1; fib(N) when N > 0 -> fib(N - 1) + fib(N - 2); fib(_) -> 0. % N Dimensions pieces(0) -> 1; pieces(N) -> N + pieces(N - 1).
This file contains 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(recur_tail). -export([fac/1, fib/1, perfect/1]). %Factorial with tail recursion fac(N) when N > 0 -> fac_tail(N, 1). fac_tail(0, Acc) -> Acc; fac_tail(N, Acc) -> fac_tail(N-1, N*Acc). %Fibonnacci sequence with tail recursion fib(N) -> fib_tail(N, 0, 1). fib_tail(0, Acc1, _) -> Acc1; fib_tail(1, _, Acc2) -> Acc2; fib_tail(N, Acc1, Acc2) -> fib_tail(N - 1, Acc2, Acc1+Acc2). perfect(N) -> perfect_tail(N, 1, 0). perfect_tail(N, N, N) -> true; perfect_tail(N, N, _) -> false; perfect_tail(N, Div, Acc) when N rem Div == 0 -> perfect_tail(N, Div+1, Acc+Div); perfect_tail(N, Div, Acc) -> perfect_tail(N, Div+1, Acc).
This file contains 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(second). -export([hypo/2, peri/2, area/2]). hypo(A,B) -> first:square(A*A + B*B). peri(A,B) -> A + B + hypo(A,B). area(A,B) -> (A*B)/2.