Created
May 8, 2020 04:39
-
-
Save mareknowak/d4601afd5c61994a5640edf7e7826717 to your computer and use it in GitHub Desktop.
Recursion examples - FP in Erlang 2.3
This file contains hidden or 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
%% @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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TDD - as you suggested :-)