DAY 27
1

## Elixir 的 Control flow

Elixir的Control Flow有四種,分別為Pattern match,
Multi-clause functions, Conditional statments

## Pattern match

``````iex(1)> {name, age} = {"Miku", 24}
{"Miku", 24}
iex(2)> name
"Miku"
iex(3)> age
24
``````

``````iex(1)> {date, time} = :calendar.local_time
{{2014, 10, 27}, {18, 15, 41}}
iex(2)> {year, month, day} = date
{2014, 10, 27}
iex(3)> {hour, minute, second} = time
{18, 15, 41}
``````

## Multi-clause functions

Multi-clause functions,在前面的例子中,

``````defmodule TestNum do
def test(x) when is_number(x) and x < 0 do
:negative
end

def test(0) do
:zero
end

def test(x) when is_number(x) and x > 0 do
:positive
end

def test(_) do
end
end
``````

``````iex(1)> c "test_num.ex"
[TestNum]
iex(2)> TestNum.test("xyz")
iex(3)> TestNum.test(:xyz)
iex(4)> TestNum.test(1)
:positive
iex(5)> TestNum.test(0)
:zero
iex(6)> TestNum.test(-1)
:negative
iex(7)> g = 2
2
iex(8)> TestNum.test(g)
:positive
``````

## Conditional statments

Elixir除了前面pattern match及Multi-clause functions,

``````def max(a, b) do
if a >= b, do: a, else: b
end

def max(a, b) do
unless a >= b, do: b, else: a
end
``````

``````cond do
expression_1 ->
...
expression_2 ->
...

...
end
``````

``````def max(a, b) do
cond do
a >= b -> a
true -> b
end
``````

``````def max(a, b) do
case a >= b do
true -> a
false -> b
end
end
``````