Skip to content

Instantly share code, notes, and snippets.

@mareknowak
Created May 8, 2020 04:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mareknowak/d4601afd5c61994a5640edf7e7826717 to your computer and use it in GitHub Desktop.
Save mareknowak/d4601afd5c61994a5640edf7e7826717 to your computer and use it in GitHub Desktop.
Recursion examples - FP in Erlang 2.3
%% @doc Recursion examples - FP in Erlang 2.3
-module(recursion).
-export([fib/1, pieces/1, test/0]).
%% @doc Give N-th element of Fibonacci sequence
fib(0) -> 0;
fib(1) -> 1;
fib(N) when N > 1 ->
fib(N-2) + fib(N-1).
test_fib() ->
1 = recursion:fib(2),
3 = recursion:fib(4),
8 = recursion:fib(6),
987 = recursion:fib(16),
% 1100087778366101931 = recursion:fib(88), % Ctrl-C Ctrl-C helps
ok.
%% @doc Step by step evaluation of fib(4)
%%
%% fib(4)
%% = fib(2) + fib(3)
%% = (fib(0) + fib(1)) + (fib(1) + fib(2))
%% = (0 + 1) + (1 + (fib(0) + fib(1)))
%% = 1 + (1 + (0 + 1))
%% = 1 + (1 + 1)
%% = 1 + 2
%% = 3
%% @doc Maximum number of pieces into which one can cut a piece of paper with N
%% straight cuts
pieces(0) -> 1; % no cuts so paper in 1 piece
pieces(1) -> 2;
pieces(N) when N > 1 ->
N + pieces(N - 1).
test_pieces() ->
4 = recursion:pieces(2),
7 = recursion:pieces(3),
11 = recursion:pieces(4),
ok.
test() ->
ok = test_fib(),
ok = test_pieces(),
ok.
@elbrujohalcon
Copy link

Nicely done! TDD FTW!!

@mareknowak
Copy link
Author

TDD - as you suggested :-)

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