Skip to content

Instantly share code, notes, and snippets.

@danielrhodeswarp
Created February 25, 2017 16:48
Show Gist options
  • Save danielrhodeswarp/de2679b638b1fea6d626b3b960346b65 to your computer and use it in GitHub Desktop.
Save danielrhodeswarp/de2679b638b1fea6d626b3b960346b65 to your computer and use it in GitHub Desktop.
For FUNCTIONAL PROGRAMMING IN ERLANG course on FutureLearn.com
-module(one_21).
-export([fib / 1, newFib / 1]).
% from lesson 1.20 ("is exponentially complex … ouch!")
fib(0) -> 0;
fib(1) -> 1;
fib(N) -> fib(N - 2) + fib(N - 1).
% "Define an efficient Fibonacci function fib/3 using
% a tail recursion with two accumulating parameters
% that hold the last two Fibonacci numbers."
% I got this bit right!
newFib(N) ->
newFib(N, 0, 1).
%newFib(N, Penultimate, Last) -> when N = 1
% 0;
%newFib(N, Penultimate, Last) -> when N = 2
% 1;
%newFib(N, Penultimate, Last) -> when N > 2
% newFib(N - 1, )
%newFib(N, Penultimate, Last) -> when N = 1
% 0;
%newFib(N, Penultimate, Last) -> when N = 2
% 1;
%newFib(N, Penultimate, Last) -> when N > 2
% newFib(N - 1, )
% from 1.22 lesson video
newFib(0, Previous, _Current) ->
Previous;
newFib(N, Previous, Current) ->
newFib(N - 1, Current, Previous + Current).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment