Last week we added two recursive functions to the calculus.erl code.
Today we are going to add a little interaction to our program, requesting to the user the number for which we want to compute the factorial.

So we’ll add a new function to ask the number and then to store (in append mode) the result into a text file.

In the code we will make use of three libraries provided by Erlang:
io, io_lib and file.

We will use io:fread to read an integer number from the standard input, the file:write_file and io_lib:fwrite to write the result into the text file.

erlang-logo-darkback
The interaction will be developed into a nwe function (calculateFac), so we need to add a new entry into the export:

-export([distance/4, fac/1, fib/1, calculateFac/0]).

The source code is very simple and auto-expicative.

% calculateFac function
calculateFac() ->
{ok , [Value]} = io:fread("Insert number to calculate factorial :", "~d" ),
fac(Value),
file:write_file("foo.txt", io_lib:fwrite("~p.\n", [fac(Value)]), [append]).

The final code for the calculus.erl will be

-module(calculus).
-export([distance/4, fac/1, fib/1, calculateFac/0]).

% distance function
distance(X0, Y0, X1, Y1) -> math:sqrt(((X1-X0)*(X1-X0)+(Y1-Y0)*(Y1-Y0))).

% factorial function
fac(0)-> 1;
fac(N) -> N * fac(N-1).

fib(N) ->
fib(N, 0, 1).

% fibonacci function
fib(0, _, B) -> B;
fib(N, A, B) ->
io:format("~p~n", [B]),
fib(N-1, B, A+B).

% calculateFac function
calculateFac() ->
{ok , [Value]} = io:fread("Insert number to calculate factorial :", "~d" ),
fac(Value),
file:write_file("foo.txt", io_lib:fwrite("~p.\n", [fac(Value)]), [append]).

Enter the erlang shell
1> c(calculus).
{ok,calculus}
2> calculus:calculateFac().
Insert number to calculate factorial :12
ok
3>
Quit the Erlang shell and verify that in the current directory there is a new file named foo.txt:
$ cat foo.txt
479001600.
Try running again the calculateFac() function to verify that new values are appended to the foo.txt file.
Gg1