Last active
October 13, 2016 11:36
-
-
Save turboMaCk/8df9c1c955e886bc84572e68fea55b33 to your computer and use it in GitHub Desktop.
Erlang recursion examples
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(func). | |
-export([fac/1, ft/1, len/1, lt/1, fib/1, tail_fib/1]). | |
%% basic recursive implementation of factorial | |
fac(N) when N == 0 -> 1; | |
fac(N) when N > 0 -> | |
N*fac(N-1). | |
%% Tail recursion implementation of factorial | |
ft(N) -> ft(N, 1). | |
ft(0, Acc) -> Acc; | |
ft(N, Acc) when N > 0 -> | |
ft(N-1, N*Acc). | |
%% List lenght recursive implementation | |
len([]) -> 0; | |
len([_]) -> 1; | |
len([_|T]) -> 1 + length(T). | |
%% List length tail recursion implementation | |
lt(L) -> lt(L, 0). | |
lt([], _) -> 0; | |
lt([_], Acc) -> Acc + 1; | |
lt([_|T], Acc) -> lt(T, Acc + 1). | |
%% Fibonacci numbers | |
fib(0) -> 0; | |
fib(1) -> 1; | |
fib(N) -> fib(N-1) + fib(N-2). | |
%% Fibonacci tail recursive implementation | |
tail_fib(0) -> 0; | |
tail_fib(1) -> 1; | |
tail_fib(N) -> tail_fib(N-2, 1, 0). | |
tail_fib(0, A, B) -> A + B; | |
tail_fib(N, A, B) -> tail_fib(N-1, A+B, A). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment