Skip to content

Instantly share code, notes, and snippets.

@turboMaCk
Created October 13, 2016 11:29
Show Gist options
  • Save turboMaCk/63240b6a83b9ff0e5a9ea91711fad996 to your computer and use it in GitHub Desktop.
Save turboMaCk/63240b6a83b9ff0e5a9ea91711fad996 to your computer and use it in GitHub Desktop.
Erlang recursion examples
-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).
%% Tal recursion implementation
ft(N) -> ft(N, 1).
ft(0, Acc) -> Acc;
ft(N, Acc) when N > 0 ->
ft(N-1, N*Acc).
%% List lenght recursiveimplementation
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).
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