Erlang
Online Erlang Compiler
main.erl is compiled with erlc from Erlang/OTP 28, then erl calls main:start() and stops when it returns. io:fread and io:get_line print their prompt and wait for you to type in the terminal.
Try it aboveHow Erlang runs here
- Versions
- Erlang/OTP 28
- Build
erlc main.erl- Run
erl -noshell -s main start -s init stop- Limits per run
- 256 MB memory, 15 s of CPU time on half a core, 2 MB of output
- Time
- Up to 10 minutes a run (30 on a paid plan); waits 2 minutes for input (5 on a paid plan)
- Sandbox
- Each run gets its own Linux sandbox with no network access. Text files your program writes next to your code open as new tabs.
An Erlang program that reads input
The module must be called main and export start/0. This one reads numbers with io:fread and a list comprehension:
-module(main). -export([start/0]). start() -> {ok, [N]} = io:fread("How many numbers? ", "~d"), Nums = [read_number(I) || I <- lists:seq(1, N)], io:format("Sorted: ~w~n", [lists:sort(Nums)]), io:format("Sum: ~w, max: ~w~n", [lists:sum(Nums), lists:max(Nums)]). read_number(I) -> {ok, [X]} = io:fread("Number " ++ integer_to_list(I) ++ ": ", "~d"), X.
$ erlc main.erl && erl -noshell -s main start -s init stop How many numbers? 4 Number 1: 12 Number 2: 7 Number 3: 30 Number 4: 5 Sorted: [5,7,12,30] Sum: 54, max: 30
Reading input in Erlang
- io:fread(Prompt, "~d") returns {ok, [Number]}. If the input isn’t a number it returns an error tuple, and a match against {ok, [N]} fails with badmatch.
- io:get_line(Prompt) returns the line as a string with its "\n". Remove it with string:trim/1 before list_to_integer/1.
- Use ~w or ~p to print terms; ~s is for strings only.
What isn’t available here
- Other modules: only main.erl is compiled, so keep your functions in it.
- rebar3 and Hex packages. OTP’s own libraries, such as lists, maps, string and ets, are there.
- The Erlang shell. There’s no 1> prompt; erl runs start/0 and exits.
Errors you’ll see
- An undef error as the run starts: start/0 isn’t exported. The run calls main:start() exactly, and a module with any other name fails earlier, at compile time.
- badarg from list_to_integer/1: the string still had its newline. Trim it first.
- A compile error saying a function is undefined, such as read_numer/1: a typo, or the wrong number of arguments.
Questions
Which Erlang version does this use?
Erlang/OTP 28. main.erl is compiled with erlc and started with erl -noshell -s main start -s init stop.
Why must my module be called main?
The run command starts main:start(), so the file needs -module(main). and -export([start/0]).
How do I read a number in Erlang?
{ok, [N]} = io:fread("Number: ", "~d"). Type the number in the terminal while the program runs.