Skip to content

Instantly share code, notes, and snippets.

@morgaine
Created February 23, 2017 14:13
Show Gist options
  • Save morgaine/64ad20a5268d2b1c8069e5c36fe75bb2 to your computer and use it in GitHub Desktop.
Save morgaine/64ad20a5268d2b1c8069e5c36fe75bb2 to your computer and use it in GitHub Desktop.
Fibonacci in Erlang, commandline interface
#! /bin/env escript
% NAME
% fib.erl -- Erlang exercise with Fibonacci numbers
%
% SYNOPSIS
% fib {from-integer} [{to-integer}]
%
% INSTALL
% ln -s fib.erl fib
%
% DESCRIPTION
% FutureLean course "Functional Programming in Erlang".
% Lesson 1.19 (part of)
% Recursion Examples
% Fibonacci Numbers.
%
% Exercise extended a little with:
% 1) use of "escript" from the commandline,
% 2) generation and display of Fib sequence from N to M,
% 3) generation of Fib sequence list using seq and map.
%
% STEP BY STEP EVALUATION
% 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
%
% TODO
% Validity of numeric commandline arguments is not yet checked.
-module(fib).
-export([fib/1, fibShow/1, fibShow/2, fibList/2]).
% A simple term generator function for the Fibonacci Sequence..
% Generates the Nth term of the Fibonacci sequence starting from 0.
fib(0) ->
0;
fib(1) ->
1;
fib(N) ->
fib(N-2) + fib(N-1).
fibShow(N) ->
io:format("fib(~p) = ~p~n", [N, fib(N)]).
fibShow(N,N) ->
fibShow(N);
fibShow(N,M) when N =< M ->
fibShow(N,M-1),
fibShow(M,M);
fibShow(N,M) ->
io:format("fib: ERROR: to-integer ~p is smaller than from-integer ~p~n", [M,N]),
halt(2).
fibList(N,M) when N =< M ->
lists:map(fib/1, lists:seq(N,M)).
main() ->
io:format("Usage: fib {from-integer} [{to-integer}]~n"),
halt(1).
main([]) ->
main();
main([NumericString]) ->
N = list_to_integer(NumericString),
fibShow(N);
main([FromNumber, ToNumber]) ->
N = list_to_integer(FromNumber),
M = list_to_integer(ToNumber),
fibShow(N,M);
main([_,_,_|_]) ->
io:format("Too many arguments.~n"),
main().
@morgaine
Copy link
Author

Example usage from commandline:

$ ./fib
Usage: fib {from-integer} [{to-integer}]
$ ./fib 0 9
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34

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