Skip to content

Instantly share code, notes, and snippets.

@morgaine
Created February 26, 2017 13:01
Show Gist options
  • Save morgaine/2d10bfdf173de95093735e56ead9ecdf to your computer and use it in GitHub Desktop.
Save morgaine/2d10bfdf173de95093735e56ead9ecdf to your computer and use it in GitHub Desktop.
Erlang: commandline interface to factorial using escript
#! /bin/env escript
%% Simplest use of Erlang's escript and commandline arguments
%% for an interface to the tail-recursive factorial function.
-module(fact).
fact(N) ->
fact(N, 1).
fact(N,Product) when N =< 1 ->
Product;
fact(N,Product) ->
fact(N-1, Product*N).
main([]) ->
io:format("Usage: fact {integer}~n"),
halt(1);
main([NumericString|_]) ->
N = list_to_integer(NumericString),
io:format("fact(~p) = ~p~n", [N, fact(N)]).
@morgaine
Copy link
Author

Hopefully this illustrates that making standalone executable scripts with Erlang really isn't much of a hurdle, even for day-1 beginners. To use it from a Unix-type commandline:

$ chmod +x fact.erl
$ ./fact.erl
Usage:  fact  {integer}
$ ./fact.erl 50
fact(50) = 30414093201713378043612608166064768844377641568960512000000000000

More usefully, two numbers would be taken from the commandline by matching on a 2-element list, and a very small additional looping function would use fact(N) to generate all factorials from the first number to the second.

@paucus
Copy link

paucus commented Mar 2, 2017

thanks for sharing, very useful to see it applied like this!

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