Skip to content

Instantly share code, notes, and snippets.

@elainenaomi
Created August 25, 2019 23:58
Show Gist options
  • Save elainenaomi/6bf816cb8b7cd3391f08064607f7488d to your computer and use it in GitHub Desktop.
Save elainenaomi/6bf816cb8b7cd3391f08064607f7488d to your computer and use it in GitHub Desktop.

Hello, Erlang

Hello, world

Create file as hello.erl

-module(hello).
-export([hello_world/0]).

hello_world() -> io:fwrite("hello, world\n").

Then

erl
> c(hello). % to compile
> hello:hello_world().

Or

erl -run hello hello_world

Factorial

#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname factorial -mnesia debug verbose
main([String]) ->
    try
        N = list_to_integer(String),
        F = fac(N),
        io:format("factorial ~w = ~w\n", [N,F])
    catch
        _:_ ->
            usage()
    end;
main(_) ->
    usage().

usage() ->
    io:format("usage: factorial integer\n"),
    halt(1).

fac(0) -> 1;
fac(N) -> N * fac(N-1).

% chmod u+x factorial
% http://erlang.org/doc/man/escript.html
% ./factorial 5

or

create the file as factorial.erl and run escript factorial.erl 5. See: http://erlang.org/doc/man/escript.html

Testing in terminal

erl
> 1 + 2.
3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment