Created
May 10, 2020 13:02
-
-
Save pppillai/f1312a1381965bd8d684ba91f6e6e25c to your computer and use it in GitHub Desktop.
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(tailrecursion). | |
-export([loop/1, fib/1, perfect/1, test_perfect_number/0, test_fib/0]). | |
loop(N) when N > 0 -> | |
io:format("~p~n", [N]), | |
loop(N-1); | |
loop(_N) -> | |
io:format("bye ~n"). | |
fib(N) -> | |
fib(N, 0, 1). | |
fib(0, Result, _Next) -> | |
Result; | |
fib(N, Result, Next) when N > 0 -> | |
fib(N-1, Next, Result + Next). | |
% fib(4) | |
% = fib(4, 0, 1) | |
% = fib(3, 1, 1) | |
% = fib(2, 1, 2) | |
% = fib(1, 2, 3) | |
% = fib(0, 3, 5) | |
% = 3. | |
% 0, 1, 1, 2, 3 | |
perfect(0) -> | |
false; | |
perfect(N) when N > 0 -> | |
perfect(N div 2, N, 0). | |
perfect(0, Number, Number) -> | |
true; | |
perfect(0, _, _) -> | |
false; | |
perfect(Divisor, Number, Accumulator) -> | |
if | |
Number rem Divisor == 0 -> | |
NewAccumulator = Accumulator + Divisor; | |
true -> | |
NewAccumulator = Accumulator | |
end, | |
perfect(Divisor-1, Number, NewAccumulator). | |
test_perfect_number() -> | |
(perfect(5) == false) andalso (perfect(6) == true) andalso (perfect(0) == false). | |
test_fib() -> | |
(fib(0) == 0) andalso (fib(1) == 1) andalso (fib(4) == 3). |
Well… we certainly didn't cover if
syntax either. If you want do work with just what's on the videos you need to use another function…
NewAccumulator = update_accumulator(Number rem Divisor, Divisor, Accumulator),
…
update_accumulator(0, Divisor, Accumulator) -> Accumulator + Divisor;
update_accumulator(_, _, Accumulator) -> Accumulator.
There are several books and resources to reed attached to the first or second video of Week 1.
will start reading.
elbrujohalcon please check https://gist.github.com/pppillai/63bce02dc627227de7181e0e68e27ccd
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am not sure we covered case syntax in the videos.
I had asked earlier should we read a text along with the videos ?