var = 1;
process(var);
println(var);
GOTO was evil because we asked, "how did I get to this point of
execution?" Mutability leaves us with, "how did I get to
this state?"
— Jessica Kerr (@jessitron)
May 11, 2013
iex> list = [1, 2, 3]
[1, 2, 3]
iex> reversed = Enum.reverse(list)
[3, 2, 1]
iex> list
[1, 2, 3]
iex> list1 = [2, 1]
[2, 1]
iex> list2 = [3 | list1]
[3, 2, 1]
2x + 3 = 5
iex> x = 1
1
iex> 2 * x + 3
5
iex> 5 = 2 * x + 3
5
iex> x = 1
1
iex> 1 = x
1
iex> 2 = x
** (MatchError) no match of right hand side value: 1
iex> {name, age} = {"John Doe", 27}
{"John Doe", 27}
iex> name
"John Doe"
iex> age
27
iex> {_, _, age} = {"John", "Doe", 27}
{"John Doe", 27}
iex> age
27
iex> {x, x} = {1, 1}
{1, 1}
iex> {x, x} = {1, 2}
** (MatchError) no match of right hand side value: {1, 2}
iex> x = 1
1
iex> x = 2
2
iex> ^x = 2
2
iex> ^x = 3
** (MatchError) no match of right hand side value: 3
iex> [head|tail] = [1, 2, 3]
[1, 2, 3]
iex> head
1
iex> tail
[2, 3]
iex> {:ok, file} = File.open(".vimrc")
{:ok, #PID<0.72.0>}
%User{confirmed: false, premium: false}
function check_user(user) {
if(!user.present?) {
redirect_to("/sign_in")
} else {
if(!user.confirmed?) {
redirect_to("/confirmation")
} elseif(!user.premium?) {
redirect_to("/pay")
}
}
}
def check_user(nil), do: redirect_to("/sign_in")
def check_user(%User{confirmed: false}), do: redirect_to("/confirmation")
def check_user(%User{premium: false}), do: redirect_to("/pay")
def check_user(user), do: user
fn
args1 -> body1
args2 -> body2
end
iex> eql = fn
...> (a, a) -> true
...> (_, _) -> false
...> end
iex> eql.(1,1)
true
iex> eql.(1,2)
false
iex> sum = fn(a) ->
...> fn(b) -> a + b end
...> end
#Function<6.90072148/1 in :erl_eval.expr/5>
iex> sum.(1).(3)
4
iex> add2 = sum.(2)
#Function<6.90072148/1 in :erl_eval.expr/5>
iex> add2.(4)
6
iex> Enum.map([1, 2, 3], fn x -> x * x end)
[1, 4, 9]
iex> Enum.sort [1, 2, 3], &( &2 < &1 )
[3, 2, 1]
iex> Enum.all? [:a, :b, :c], &is_atom(&1)
true
iex> Enum.map ["a", "B", "c"], &String.upcase &1
["A", "B", "C"]
iex> Enum.map ["a", "B", "c"], &String.to_atom/1
[:a, :B, :c]
defmodule Lst do
def size([]), do: 0
def size([_head|tail]), do: 1 + size(tail)
end
iex> Lst.size([])
0
iex> Lst.size([1,2,3,4,5])
5