2013-07-02 15:07:34 +04:00
|
|
|
---
|
|
|
|
language: elixir
|
2013-07-04 09:59:13 +04:00
|
|
|
contributors:
|
|
|
|
- ["Joao Marques", "http://github.com/mrshankly"]
|
2014-10-18 15:00:32 +04:00
|
|
|
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
|
2016-07-12 11:07:38 +03:00
|
|
|
- ["Ryan Plant", "https://github.com/ryanplant-au"]
|
2017-08-15 21:58:51 +03:00
|
|
|
- ["Ev Bogdanov", "https://github.com/evbogdanov"]
|
2013-07-02 15:07:34 +04:00
|
|
|
filename: learnelixir.ex
|
|
|
|
---
|
|
|
|
|
2013-07-03 09:47:37 +04:00
|
|
|
Elixir is a modern functional language built on top of the Erlang VM.
|
|
|
|
It's fully compatible with Erlang, but features a more standard syntax
|
|
|
|
and many more features.
|
|
|
|
|
2014-03-31 14:00:57 +04:00
|
|
|
```elixir
|
2013-07-03 09:47:37 +04:00
|
|
|
|
2014-04-14 22:04:44 +04:00
|
|
|
# Single line comments start with a number symbol.
|
2013-07-02 15:07:34 +04:00
|
|
|
|
2013-07-03 02:37:18 +04:00
|
|
|
# There's no multi-line comment,
|
|
|
|
# but you can stack multiple comments.
|
|
|
|
|
|
|
|
# To use the elixir shell use the `iex` command.
|
|
|
|
# Compile your modules with the `elixirc` command.
|
|
|
|
|
|
|
|
# Both should be in your path if you installed elixir correctly.
|
|
|
|
|
|
|
|
## ---------------------------
|
2013-07-02 15:07:34 +04:00
|
|
|
## -- Basic types
|
2013-07-03 02:37:18 +04:00
|
|
|
## ---------------------------
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# There are numbers
|
|
|
|
3 # integer
|
|
|
|
0x1F # integer
|
|
|
|
3.0 # float
|
|
|
|
|
|
|
|
# Atoms, that are literals, a constant with name. They start with `:`.
|
|
|
|
:hello # atom
|
|
|
|
|
2013-07-09 10:37:41 +04:00
|
|
|
# Tuples that are stored contiguously in memory.
|
2013-07-02 15:07:34 +04:00
|
|
|
{1,2,3} # tuple
|
|
|
|
|
|
|
|
# We can access a tuple element with the `elem` function:
|
2013-07-03 02:23:49 +04:00
|
|
|
elem({1, 2, 3}, 0) #=> 1
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# Lists that are implemented as linked lists.
|
|
|
|
[1,2,3] # list
|
|
|
|
|
|
|
|
# We can access the head and tail of a list as follows:
|
|
|
|
[head | tail] = [1,2,3]
|
2013-07-03 02:23:49 +04:00
|
|
|
head #=> 1
|
|
|
|
tail #=> [2,3]
|
2013-07-02 15:07:34 +04:00
|
|
|
|
2013-07-09 10:37:41 +04:00
|
|
|
# In elixir, just like in Erlang, the `=` denotes pattern matching and
|
2013-07-02 15:07:34 +04:00
|
|
|
# not an assignment.
|
|
|
|
#
|
|
|
|
# This means that the left-hand side (pattern) is matched against a
|
|
|
|
# right-hand side.
|
|
|
|
#
|
|
|
|
# This is how the above example of accessing the head and tail of a list works.
|
|
|
|
|
|
|
|
# A pattern match will error when the sides don't match, in this example
|
|
|
|
# the tuples have different sizes.
|
2013-07-03 09:47:37 +04:00
|
|
|
# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2}
|
2013-07-02 15:07:34 +04:00
|
|
|
|
2014-10-18 15:00:32 +04:00
|
|
|
# There are also binaries
|
2013-07-02 15:07:34 +04:00
|
|
|
<<1,2,3>> # binary
|
|
|
|
|
|
|
|
# Strings and char lists
|
|
|
|
"hello" # string
|
|
|
|
'hello' # char list
|
|
|
|
|
2013-07-03 02:23:49 +04:00
|
|
|
# Multi-line strings
|
|
|
|
"""
|
|
|
|
I'm a multi-line
|
|
|
|
string.
|
|
|
|
"""
|
|
|
|
#=> "I'm a multi-line\nstring.\n"
|
|
|
|
|
2013-07-02 15:07:34 +04:00
|
|
|
# Strings are all encoded in UTF-8:
|
2013-07-03 02:23:49 +04:00
|
|
|
"héllò" #=> "héllò"
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# Strings are really just binaries, and char lists are just lists.
|
2013-07-03 02:23:49 +04:00
|
|
|
<<?a, ?b, ?c>> #=> "abc"
|
|
|
|
[?a, ?b, ?c] #=> 'abc'
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# `?a` in elixir returns the ASCII integer for the letter `a`
|
2013-07-03 02:23:49 +04:00
|
|
|
?a #=> 97
|
|
|
|
|
|
|
|
# To concatenate lists use `++`, for binaries use `<>`
|
|
|
|
[1,2,3] ++ [4,5] #=> [1,2,3,4,5]
|
|
|
|
'hello ' ++ 'world' #=> 'hello world'
|
2013-07-02 15:07:34 +04:00
|
|
|
|
2013-07-03 02:23:49 +04:00
|
|
|
<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>>
|
|
|
|
"hello " <> "world" #=> "hello world"
|
2013-07-02 15:07:34 +04:00
|
|
|
|
2015-01-31 15:32:21 +03:00
|
|
|
# Ranges are represented as `start..end` (both inclusive)
|
|
|
|
1..10 #=> 1..10
|
|
|
|
lower..upper = 1..10 # Can use pattern matching on ranges as well
|
|
|
|
[lower, upper] #=> [1, 10]
|
|
|
|
|
2016-07-12 11:07:38 +03:00
|
|
|
# Maps are key-value pairs
|
|
|
|
genders = %{"david" => "male", "gillian" => "female"}
|
|
|
|
genders["david"] #=> "male"
|
|
|
|
|
|
|
|
# Maps with atom keys can be used like this
|
|
|
|
genders = %{david: "male", gillian: "female"}
|
|
|
|
genders.gillian #=> "female"
|
|
|
|
|
2013-07-02 16:16:12 +04:00
|
|
|
## ---------------------------
|
2013-07-02 15:07:34 +04:00
|
|
|
## -- Operators
|
2013-07-02 16:16:12 +04:00
|
|
|
## ---------------------------
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# Some math
|
2013-07-03 02:23:49 +04:00
|
|
|
1 + 1 #=> 2
|
|
|
|
10 - 5 #=> 5
|
|
|
|
5 * 2 #=> 10
|
|
|
|
10 / 2 #=> 5.0
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# In elixir the operator `/` always returns a float.
|
|
|
|
|
|
|
|
# To do integer division use `div`
|
2013-07-03 02:23:49 +04:00
|
|
|
div(10, 2) #=> 5
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# To get the division remainder use `rem`
|
2013-07-03 02:23:49 +04:00
|
|
|
rem(10, 3) #=> 1
|
2013-07-02 15:07:34 +04:00
|
|
|
|
2014-10-18 15:00:32 +04:00
|
|
|
# There are also boolean operators: `or`, `and` and `not`.
|
2013-07-02 15:07:34 +04:00
|
|
|
# These operators expect a boolean as their first argument.
|
2013-07-03 02:23:49 +04:00
|
|
|
true and true #=> true
|
|
|
|
false or true #=> true
|
2017-08-15 21:58:51 +03:00
|
|
|
# 1 and true
|
|
|
|
#=> ** (BadBooleanError) expected a boolean on left-side of "and", got: 1
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# Elixir also provides `||`, `&&` and `!` which accept arguments of any type.
|
|
|
|
# All values except `false` and `nil` will evaluate to true.
|
2013-07-03 02:23:49 +04:00
|
|
|
1 || true #=> 1
|
|
|
|
false && 1 #=> false
|
|
|
|
nil && 20 #=> nil
|
|
|
|
!true #=> false
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# For comparisons we have: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>`
|
2013-07-03 02:23:49 +04:00
|
|
|
1 == 1 #=> true
|
|
|
|
1 != 1 #=> false
|
|
|
|
1 < 2 #=> true
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# `===` and `!==` are more strict when comparing integers and floats:
|
2013-07-03 02:23:49 +04:00
|
|
|
1 == 1.0 #=> true
|
|
|
|
1 === 1.0 #=> false
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# We can also compare two different data types:
|
2013-07-03 02:23:49 +04:00
|
|
|
1 < :hello #=> true
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# The overall sorting order is defined below:
|
2013-07-03 09:47:37 +04:00
|
|
|
# number < atom < reference < functions < port < pid < tuple < list < bit string
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# To quote Joe Armstrong on this: "The actual order is not important,
|
|
|
|
# but that a total ordering is well defined is important."
|
|
|
|
|
2013-07-02 16:16:12 +04:00
|
|
|
## ---------------------------
|
2013-07-02 15:07:34 +04:00
|
|
|
## -- Control Flow
|
2013-07-02 16:16:12 +04:00
|
|
|
## ---------------------------
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# `if` expression
|
|
|
|
if false do
|
2013-07-03 03:03:44 +04:00
|
|
|
"This will never be seen"
|
2013-07-02 15:07:34 +04:00
|
|
|
else
|
2013-07-03 03:03:44 +04:00
|
|
|
"This will"
|
2013-07-02 15:07:34 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
# There's also `unless`
|
|
|
|
unless true do
|
2013-07-03 03:03:44 +04:00
|
|
|
"This will never be seen"
|
2013-07-02 15:07:34 +04:00
|
|
|
else
|
2013-07-03 03:03:44 +04:00
|
|
|
"This will"
|
2013-07-02 15:07:34 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
# Remember pattern matching? Many control-flow structures in elixir rely on it.
|
|
|
|
|
|
|
|
# `case` allows us to compare a value against many patterns:
|
|
|
|
case {:one, :two} do
|
2013-07-03 03:03:44 +04:00
|
|
|
{:four, :five} ->
|
|
|
|
"This won't match"
|
|
|
|
{:one, x} ->
|
2016-03-04 19:02:20 +03:00
|
|
|
"This will match and bind `x` to `:two` in this clause"
|
2013-07-03 03:03:44 +04:00
|
|
|
_ ->
|
|
|
|
"This will match any value"
|
2013-07-02 15:07:34 +04:00
|
|
|
end
|
|
|
|
|
2014-10-18 15:00:32 +04:00
|
|
|
# It's common to bind the value to `_` if we don't need it.
|
2013-07-02 15:07:34 +04:00
|
|
|
# For example, if only the head of a list matters to us:
|
2013-07-03 03:03:44 +04:00
|
|
|
[head | _] = [1,2,3]
|
2013-07-03 02:23:49 +04:00
|
|
|
head #=> 1
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# For better readability we can do the following:
|
|
|
|
[head | _tail] = [:a, :b, :c]
|
2013-07-03 02:23:49 +04:00
|
|
|
head #=> :a
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
# `cond` lets us check for many conditions at the same time.
|
|
|
|
# Use `cond` instead of nesting many `if` expressions.
|
|
|
|
cond do
|
2013-07-03 03:03:44 +04:00
|
|
|
1 + 1 == 3 ->
|
|
|
|
"I will never be seen"
|
|
|
|
2 * 5 == 12 ->
|
|
|
|
"Me neither"
|
|
|
|
1 + 2 == 3 ->
|
|
|
|
"But I will"
|
2013-07-02 15:07:34 +04:00
|
|
|
end
|
|
|
|
|
2015-06-24 20:50:39 +03:00
|
|
|
# It is common to set the last condition equal to `true`, which will always match.
|
2013-07-02 15:07:34 +04:00
|
|
|
cond do
|
2013-07-03 03:03:44 +04:00
|
|
|
1 + 1 == 3 ->
|
|
|
|
"I will never be seen"
|
|
|
|
2 * 5 == 12 ->
|
|
|
|
"Me neither"
|
|
|
|
true ->
|
|
|
|
"But I will (this is essentially an else)"
|
2013-07-02 15:07:34 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
# `try/catch` is used to catch values that are thrown, it also supports an
|
2014-06-07 18:45:57 +04:00
|
|
|
# `after` clause that is invoked whether or not a value is caught.
|
2013-07-02 15:07:34 +04:00
|
|
|
try do
|
2013-07-03 03:03:44 +04:00
|
|
|
throw(:hello)
|
2013-07-02 15:07:34 +04:00
|
|
|
catch
|
2013-07-03 03:03:44 +04:00
|
|
|
message -> "Got #{message}."
|
2013-07-02 15:07:34 +04:00
|
|
|
after
|
2013-07-03 03:03:44 +04:00
|
|
|
IO.puts("I'm the after clause.")
|
2013-07-02 15:07:34 +04:00
|
|
|
end
|
2013-07-03 02:23:49 +04:00
|
|
|
#=> I'm the after clause
|
2013-07-03 03:03:44 +04:00
|
|
|
# "Got :hello"
|
2013-07-02 15:07:34 +04:00
|
|
|
|
|
|
|
## ---------------------------
|
|
|
|
## -- Modules and Functions
|
|
|
|
## ---------------------------
|
|
|
|
|
2013-07-02 16:16:12 +04:00
|
|
|
# Anonymous functions (notice the dot)
|
|
|
|
square = fn(x) -> x * x end
|
|
|
|
square.(5) #=> 25
|
|
|
|
|
2013-07-03 09:47:37 +04:00
|
|
|
# They also accept many clauses and guards.
|
|
|
|
# Guards let you fine tune pattern matching,
|
2013-07-03 02:23:49 +04:00
|
|
|
# they are indicated by the `when` keyword:
|
2013-07-02 16:16:12 +04:00
|
|
|
f = fn
|
2013-07-03 03:03:44 +04:00
|
|
|
x, y when x > 0 -> x + y
|
|
|
|
x, y -> x * y
|
2013-07-02 16:16:12 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
f.(1, 3) #=> 4
|
|
|
|
f.(-1, 3) #=> -3
|
|
|
|
|
2013-07-03 02:23:49 +04:00
|
|
|
# Elixir also provides many built-in functions.
|
|
|
|
# These are available in the current scope.
|
|
|
|
is_number(10) #=> true
|
|
|
|
is_list("hello") #=> false
|
|
|
|
elem({1,2,3}, 0) #=> 1
|
|
|
|
|
2013-07-02 16:16:12 +04:00
|
|
|
# You can group several functions into a module. Inside a module use `def`
|
|
|
|
# to define your functions.
|
|
|
|
defmodule Math do
|
2013-07-03 03:03:44 +04:00
|
|
|
def sum(a, b) do
|
|
|
|
a + b
|
|
|
|
end
|
2013-07-02 16:16:12 +04:00
|
|
|
|
2013-07-03 03:03:44 +04:00
|
|
|
def square(x) do
|
|
|
|
x * x
|
|
|
|
end
|
2013-07-02 16:16:12 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
Math.sum(1, 2) #=> 3
|
2013-07-03 09:47:37 +04:00
|
|
|
Math.square(3) #=> 9
|
2013-07-02 16:16:12 +04:00
|
|
|
|
2013-07-03 03:03:44 +04:00
|
|
|
# To compile our simple Math module save it as `math.ex` and use `elixirc`
|
|
|
|
# in your terminal: elixirc math.ex
|
2013-07-02 16:16:12 +04:00
|
|
|
|
2013-07-03 02:23:49 +04:00
|
|
|
# Inside a module we can define functions with `def` and private functions with `defp`.
|
2013-07-02 16:16:12 +04:00
|
|
|
# A function defined with `def` is available to be invoked from other modules,
|
|
|
|
# a private function can only be invoked locally.
|
|
|
|
defmodule PrivateMath do
|
2013-07-03 03:03:44 +04:00
|
|
|
def sum(a, b) do
|
|
|
|
do_sum(a, b)
|
|
|
|
end
|
2013-07-02 16:16:12 +04:00
|
|
|
|
2013-07-03 03:03:44 +04:00
|
|
|
defp do_sum(a, b) do
|
|
|
|
a + b
|
|
|
|
end
|
2013-07-02 16:16:12 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
PrivateMath.sum(1, 2) #=> 3
|
2013-07-03 09:47:37 +04:00
|
|
|
# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError)
|
2013-07-02 16:16:12 +04:00
|
|
|
|
2018-10-08 19:17:24 +03:00
|
|
|
# Function declarations also support guards and multiple clauses.
|
|
|
|
# When a function with multiple clauses is called, the first function
|
|
|
|
# that satisfies the clause will be invoked.
|
|
|
|
# Example: invoking area({:circle, 3}) will call the second area
|
|
|
|
# function defined below, not the first:
|
2013-07-02 16:16:12 +04:00
|
|
|
defmodule Geometry do
|
2013-07-03 03:03:44 +04:00
|
|
|
def area({:rectangle, w, h}) do
|
|
|
|
w * h
|
|
|
|
end
|
2013-07-02 16:16:12 +04:00
|
|
|
|
2013-07-03 03:03:44 +04:00
|
|
|
def area({:circle, r}) when is_number(r) do
|
|
|
|
3.14 * r * r
|
|
|
|
end
|
2013-07-02 16:16:12 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
Geometry.area({:rectangle, 2, 3}) #=> 6
|
|
|
|
Geometry.area({:circle, 3}) #=> 28.25999999999999801048
|
2013-07-03 09:47:37 +04:00
|
|
|
# Geometry.area({:circle, "not_a_number"})
|
2013-07-03 03:03:44 +04:00
|
|
|
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
|
2013-07-02 16:16:12 +04:00
|
|
|
|
|
|
|
# Due to immutability, recursion is a big part of elixir
|
|
|
|
defmodule Recursion do
|
2013-07-03 03:03:44 +04:00
|
|
|
def sum_list([head | tail], acc) do
|
|
|
|
sum_list(tail, acc + head)
|
|
|
|
end
|
2013-07-02 16:16:12 +04:00
|
|
|
|
2013-07-03 03:03:44 +04:00
|
|
|
def sum_list([], acc) do
|
|
|
|
acc
|
|
|
|
end
|
2013-07-02 16:16:12 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
Recursion.sum_list([1,2,3], 0) #=> 6
|
|
|
|
|
2013-07-03 02:23:49 +04:00
|
|
|
# Elixir modules support attributes, there are built-in attributes and you
|
2014-10-18 15:00:32 +04:00
|
|
|
# may also add custom ones.
|
2013-07-03 02:23:49 +04:00
|
|
|
defmodule MyMod do
|
2013-07-03 03:03:44 +04:00
|
|
|
@moduledoc """
|
|
|
|
This is a built-in attribute on a example module.
|
|
|
|
"""
|
2013-07-03 02:23:49 +04:00
|
|
|
|
2013-07-03 03:03:44 +04:00
|
|
|
@my_data 100 # This is a custom attribute.
|
|
|
|
IO.inspect(@my_data) #=> 100
|
2013-07-03 02:23:49 +04:00
|
|
|
end
|
2013-07-02 16:16:12 +04:00
|
|
|
|
2016-10-09 14:28:23 +03:00
|
|
|
# The pipe operator |> allows you to pass the output of an expression
|
|
|
|
# as the first parameter into a function.
|
|
|
|
|
|
|
|
Range.new(1,10)
|
|
|
|
|> Enum.map(fn x -> x * x end)
|
|
|
|
|> Enum.filter(fn x -> rem(x, 2) == 0 end)
|
|
|
|
#=> [4, 16, 36, 64, 100]
|
|
|
|
|
2013-07-02 16:16:12 +04:00
|
|
|
## ---------------------------
|
2014-10-18 15:00:32 +04:00
|
|
|
## -- Structs and Exceptions
|
2013-07-02 16:16:12 +04:00
|
|
|
## ---------------------------
|
|
|
|
|
2014-10-18 15:00:32 +04:00
|
|
|
# Structs are extensions on top of maps that bring default values,
|
|
|
|
# compile-time guarantees and polymorphism into Elixir.
|
|
|
|
defmodule Person do
|
|
|
|
defstruct name: nil, age: 0, height: 0
|
|
|
|
end
|
2013-07-02 16:16:12 +04:00
|
|
|
|
2014-10-18 15:00:32 +04:00
|
|
|
joe_info = %Person{ name: "Joe", age: 30, height: 180 }
|
|
|
|
#=> %Person{age: 30, height: 180, name: "Joe"}
|
2013-07-02 15:07:34 +04:00
|
|
|
|
2013-07-02 16:16:12 +04:00
|
|
|
# Access the value of name
|
|
|
|
joe_info.name #=> "Joe"
|
|
|
|
|
|
|
|
# Update the value of age
|
2014-10-18 15:00:32 +04:00
|
|
|
older_joe_info = %{ joe_info | age: 31 }
|
|
|
|
#=> %Person{age: 31, height: 180, name: "Joe"}
|
2013-07-02 16:16:12 +04:00
|
|
|
|
2013-07-03 02:23:49 +04:00
|
|
|
# The `try` block with the `rescue` keyword is used to handle exceptions
|
|
|
|
try do
|
2013-07-03 03:03:44 +04:00
|
|
|
raise "some error"
|
2013-07-03 02:23:49 +04:00
|
|
|
rescue
|
2013-07-03 03:03:44 +04:00
|
|
|
RuntimeError -> "rescued a runtime error"
|
|
|
|
_error -> "this will rescue any error"
|
2013-07-03 02:23:49 +04:00
|
|
|
end
|
2015-11-05 07:28:26 +03:00
|
|
|
#=> "rescued a runtime error"
|
2013-07-03 02:23:49 +04:00
|
|
|
|
|
|
|
# All exceptions have a message
|
|
|
|
try do
|
2013-07-03 03:03:44 +04:00
|
|
|
raise "some error"
|
2013-07-03 02:23:49 +04:00
|
|
|
rescue
|
2013-07-03 03:03:44 +04:00
|
|
|
x in [RuntimeError] ->
|
|
|
|
x.message
|
2013-07-03 02:23:49 +04:00
|
|
|
end
|
2015-11-05 07:28:26 +03:00
|
|
|
#=> "some error"
|
2013-07-02 16:16:12 +04:00
|
|
|
|
|
|
|
## ---------------------------
|
|
|
|
## -- Concurrency
|
|
|
|
## ---------------------------
|
2013-07-02 15:07:34 +04:00
|
|
|
|
2013-07-03 02:23:49 +04:00
|
|
|
# Elixir relies on the actor model for concurrency. All we need to write
|
|
|
|
# concurrent programs in elixir are three primitives: spawning processes,
|
|
|
|
# sending messages and receiving messages.
|
|
|
|
|
|
|
|
# To start a new process we use the `spawn` function, which takes a function
|
|
|
|
# as argument.
|
|
|
|
f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245>
|
|
|
|
spawn(f) #=> #PID<0.40.0>
|
|
|
|
|
|
|
|
# `spawn` returns a pid (process identifier), you can use this pid to send
|
2014-05-20 09:51:34 +04:00
|
|
|
# messages to the process. To do message passing we use the `send` operator.
|
2013-07-03 02:23:49 +04:00
|
|
|
# For all of this to be useful we need to be able to receive messages. This is
|
2014-09-18 21:41:47 +04:00
|
|
|
# achieved with the `receive` mechanism:
|
2015-10-18 02:37:47 +03:00
|
|
|
|
|
|
|
# The `receive do` block is used to listen for messages and process
|
|
|
|
# them when they are received. A `receive do` block will only
|
|
|
|
# process one received message. In order to process multiple
|
|
|
|
# messages, a function with a `receive do` block must recursively
|
|
|
|
# call itself to get into the `receive do` block again.
|
|
|
|
|
2013-07-03 02:23:49 +04:00
|
|
|
defmodule Geometry do
|
2013-07-03 03:03:44 +04:00
|
|
|
def area_loop do
|
|
|
|
receive do
|
|
|
|
{:rectangle, w, h} ->
|
|
|
|
IO.puts("Area = #{w * h}")
|
|
|
|
area_loop()
|
|
|
|
{:circle, r} ->
|
|
|
|
IO.puts("Area = #{3.14 * r * r}")
|
|
|
|
area_loop()
|
|
|
|
end
|
|
|
|
end
|
2013-07-03 02:23:49 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
# Compile the module and create a process that evaluates `area_loop` in the shell
|
|
|
|
pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0>
|
2015-10-18 03:49:58 +03:00
|
|
|
# Alternatively
|
2015-10-16 03:59:18 +03:00
|
|
|
pid = spawn(Geometry, :area_loop, [])
|
2013-07-03 02:23:49 +04:00
|
|
|
|
|
|
|
# Send a message to `pid` that will match a pattern in the receive statement
|
2014-05-20 09:51:34 +04:00
|
|
|
send pid, {:rectangle, 2, 3}
|
2013-07-03 02:23:49 +04:00
|
|
|
#=> Area = 6
|
|
|
|
# {:rectangle,2,3}
|
|
|
|
|
2014-05-20 09:51:34 +04:00
|
|
|
send pid, {:circle, 2}
|
2013-07-03 02:23:49 +04:00
|
|
|
#=> Area = 12.56000000000000049738
|
|
|
|
# {:circle,2}
|
2013-07-03 02:37:18 +04:00
|
|
|
|
|
|
|
# The shell is also a process, you can use `self` to get the current pid
|
|
|
|
self() #=> #PID<0.27.0>
|
2016-07-12 11:07:38 +03:00
|
|
|
|
|
|
|
## ---------------------------
|
|
|
|
## -- Agents
|
|
|
|
## ---------------------------
|
|
|
|
|
|
|
|
# An agent is a process that keeps track of some changing value
|
|
|
|
|
|
|
|
# Create an agent with `Agent.start_link`, passing in a function
|
|
|
|
# The initial state of the agent will be whatever that function returns
|
2017-03-15 12:06:31 +03:00
|
|
|
{ok, my_agent} = Agent.start_link(fn -> ["red", "green"] end)
|
2016-07-12 11:07:38 +03:00
|
|
|
|
|
|
|
# `Agent.get` takes an agent name and a `fn` that gets passed the current state
|
|
|
|
# Whatever that `fn` returns is what you'll get back
|
2017-03-15 12:06:31 +03:00
|
|
|
Agent.get(my_agent, fn colors -> colors end) #=> ["red", "green"]
|
2016-07-12 11:07:38 +03:00
|
|
|
|
|
|
|
# Update the agent's state the same way
|
|
|
|
Agent.update(my_agent, fn colors -> ["blue" | colors] end)
|
2013-07-02 16:16:12 +04:00
|
|
|
```
|
2013-07-03 02:23:49 +04:00
|
|
|
|
|
|
|
## References
|
|
|
|
|
2016-02-16 20:38:53 +03:00
|
|
|
* [Getting started guide](http://elixir-lang.org/getting-started/introduction.html) from the [Elixir website](http://elixir-lang.org)
|
2013-07-03 02:23:49 +04:00
|
|
|
* [Elixir Documentation](http://elixir-lang.org/docs/master/)
|
2014-10-18 15:00:32 +04:00
|
|
|
* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) by Dave Thomas
|
|
|
|
* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
|
2013-07-03 02:23:49 +04:00
|
|
|
* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) by Fred Hebert
|
2014-10-18 15:00:32 +04:00
|
|
|
* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong
|