Skip to content

Instantly share code, notes, and snippets.

@pppillai
Created May 10, 2020 13:02
Show Gist options
  • Save pppillai/f1312a1381965bd8d684ba91f6e6e25c to your computer and use it in GitHub Desktop.
Save pppillai/f1312a1381965bd8d684ba91f6e6e25c to your computer and use it in GitHub Desktop.
-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).
@pppillai
Copy link
Author

I am not sure we covered case syntax in the videos.
I had asked earlier should we read a text along with the videos ?

@elbrujohalcon
Copy link

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.

@pppillai
Copy link
Author

will start reading.

@pppillai
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment