$ brew update
$ brew install erlang
$ brew install elixir
# open editor (like IRB)
$ iex
# load file and editor
$ iex "path/to/filename.ex"
# start a new project
$ mix new project_name
# load all modules in project directory
$ iex -S mix
# load a file
iex> c “path/to/filename.ex”
# reload an elixir module
iex> r ModuleName
# get previous console output (underscore in rails console)
iex> v
iex> add1 = fn(x) -> x + 1 end
iex> add1 = &(&1+1)
iex> add1.(4)
5
iex> fun = fn(x) -> Kernel.is_atom(x) end
iex> fun = &Kernel.is_atom/1
iex> fun.(:atom)
true
defmodule Handler do
def handle(request) do
conv = parse(request)
conv = route(conv)
format_response(conv)
end
# or
def handle(request) do
format_response(route(parse(request)))
end
# with pipes!
def handle(request) do
request
|> parse
|> route
|> format_response
end
end
defmodule User do
defstruct name: "John Doe", age: nil
end
iex>
name
=> undefined
%{name: name} = %User{}
name
=> John Doe
defmodule User do
defstruct name: "Jane Doe", age: 18
def serve_drinks(%User{age: age, name: name}) when age >= 21 do
IO.puts "Hello #{name}, you are over 21. Enjoy drinking!"
end
def serve_drinks(%User{age: age, name: name}) do
IO.puts "Sorry #{name}, you are not over 21. No booze for you!"
end
end
iex>
user = %User{}
=> %User{age: 18, name: "John Doe"}
User.serve_drinks(user)
=> Sorry John Doe, you are not over 21. No booze for you!
defmodule Loop do
def over([head | tail]) do
IO.puts "This is now the head: #{head}"
over(tail)
end
def over([]) do
IO.puts "List is empty now."
end
end
iex>
list = [1,2,3]
Loop.over(list)
=>
This is now the head: 1
This is now the head: 2
This is now the head: 3
List is empty now.
:ok
iex> {:ok, result} = {:ok, 13}
{:ok, 13}
iex> result
13
iex> {:ok, result} = {:error, :oops}
** (MatchError) no match of right hand side value: {:error, :oops}
current_process = self()
# Spawn an Elixir process (not an operating system one!)
spawn_link(fn ->
send current_process, {:msg, "hello world"}
end)
# Accessing messages in processor mailbox
iex> Process.info(current_process, :messages)
=> {:messages, [msg: "hello world"]}
# Block until the message is received
receive do
{:msg, contents} -> IO.puts contents
end
PID
pid = self()
#PID<0.317.0>
string = "#PID<0.317.0>"
string
|> :erlang.binary_to_list
|> :erlang.list_to_pid
https://elixir-examples.github.io/examples/elixir-and-ruby-comparison