Elixir
Online Elixir Compiler
Your code runs as a script with elixir main.exs, on Elixir 1.19 and Erlang/OTP 28. IO.gets prints its prompt and waits for you to type in the terminal.
Try it aboveHow Elixir runs here
- Versions
- Elixir 1.19 on Erlang/OTP 28
- Run
elixir main.exs- 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 Elixir script that reads input
This main.exs reads numbers in a comprehension and pipes them through Enum:
n = IO.gets("How many numbers? ") |> String.trim() |> String.to_integer() nums = for i <- 1..n do IO.gets("Number #{i}: ") |> String.trim() |> String.to_integer() end IO.puts("Sorted: #{nums |> Enum.sort() |> Enum.join(" ")}") IO.puts("Sum: #{Enum.sum(nums)}") IO.puts("Even: #{nums |> Enum.filter(&(rem(&1, 2) == 0)) |> Enum.join(", ")}")
$ elixir main.exs How many numbers? 4 Number 1: 12 Number 2: 7 Number 3: 30 Number 4: 5 Sorted: 5 7 12 30 Sum: 54 Even: 12, 30
Reading input in Elixir
- IO.gets(prompt) returns the line with its "\n". String.trim() it before String.to_integer(), or the conversion raises.
- For several numbers on one line: IO.gets("") |> String.split() |> Enum.map(&String.to_integer/1).
- IO.read(:eof) and Enum over IO.stream() wait for the end of input, which this terminal never sends. Read a count first, or stop on an empty line.
What isn’t available here
- Mix projects and Hex packages: no mix.exs, and Mix.install/1 can’t download without a network. Phoenix, Ecto and Jason are out; Elixir’s standard library and OTP are there.
- IEx. The script runs from top to bottom without an interactive prompt.
- Only main.exs runs. A second script can be loaded with Code.require_file("helpers.exs").
Errors you’ll see
- ArgumentError saying the argument is not a textual representation of an integer, from String.to_integer/1: the string still had its newline, or wasn’t a number.
- UndefinedFunctionError, function … is undefined: a misspelled module or function name, or the wrong arity, such as Enum.sum/2.
- ArithmeticError, bad argument in arithmetic expression: math on a string, often input you didn’t convert.
Questions
Which Elixir version does this use?
Elixir 1.19 on Erlang/OTP 28, running main.exs as a script.
Can I use Hex packages or Phoenix?
No. There’s no Mix project and runs are offline, so only the standard library and OTP are available.
How do I read a number from input in Elixir?
IO.gets("Number: ") |> String.trim() |> String.to_integer(). Type it in the terminal while the script runs.