The following examples can be run in an iex
shell or saved in a file and run from the
command line by typing elixir ''''. Classic
Hello world example: iex> IO.puts("Hello World!") Hello World! Pipe operator: iex> "Elixir" |> String.graphemes() |> Enum.frequencies() %{"E" => 1, "i" => 2, "l" => 1, "r" => 1, "x" => 1} iex> %{values: 1..5} |> Map.get(:values) |> Enum.map(& &1 * 2) [2, 4, 6, 8, 10] iex> %{values: 1..5} |> Map.get(:values) |> Enum.map(& &1 * 2) |> Enum.sum() 30
Pattern matching (a.k.a. destructuring): iex> %{left: x} = %{left: 5, right: 8} iex> x 5 iex> {:ok, [_ | rest]} = {:ok, [1, 2, 3]} iex> rest [2, 3] Pattern matching with multiple clauses: iex> case File.read("path/to/file") do iex> {:ok, contents} -> IO.puts("found file: #{contents}") iex> {:error, reason} -> IO.puts("missing file: #{reason}") iex> end
List comprehension: iex> for n Asynchronously reading files with streams: 1..5 Multiple function bodies with
guards: def fib(n) when n in [0, 1], do: n def fib(n), do: fib(n-2) + fib(n-1) Relational databases with the Ecto library: schema "weather" do field :city # Defaults to type :string field :temp_lo, :integer field :temp_hi, :integer field :prcp, :float, default: 0.0 end Weather |> where(city: "Kraków") |> order_by(:temp_lo) |> limit(10) |> Repo.all Sequentially spawning a thousand processes: for num IO.puts("#{num * 2}") end
Asynchronously performing a task: task = Task.async fn -> perform_complex_action() end other_time_consuming_action() Task.await task == See also ==