DAY 28
1

## Elixir 的 Loops 與 iteration

Elixir的loops,嗯.....

## 遞迴與尾遞迴

``````defmodule NaturalNums do
def print(1), do: IO.puts(1)

def print(n) do
print(n - 1)
IO.puts(n)
end
end
``````

``````iex(1)> c "natural_nums.ex"
[NaturalNums]
iex(2)> NaturalNums.print(3)
1
2
3
:ok
``````

``````defmodule ListHelper do
def sum([]), do: 0

end
end

defmodule ListHelper do
def sum(list) do
do_sum(0, list)
end

defp do_sum(current_sum, []) do
current_sum
end

defp do_sum(current_sum, [head | tail]) do
do_sum(new_sum, tail)
end
end
``````

## Higher-order functions

Enum模組裡的函數,搭配Higer-order functions

``````iex(1)> Enum.each(
...(1)>   [1,2,3],
...(1)>   fn(x) -> IO.puts(x) end
...(1)> )
1
2
3
:ok

iex(2)> Enum.map(
...(2)>   [1,2,3],
...(2)>   &(&1 * 2)
...(2)> )
[2, 4, 6]

iex(3)> Enum.filter(
...(3)>   [1,2,3],
...(3)>   fn(x) -> rem(x, 2) == 1 end
...(3)> )
[1, 3]

iex(4)> Enum.filter(
...(4)>   [1,2,3],
...(4)>   &(rem(&1,2) == 1)
...(4)> )
[1, 3]
``````

Enum的 Enum.each, Enum.map, Enum.filter 三個函數,

``````var sum = 0;

[1,2,3].forEach(function(element) {
sum += element;
})
``````

``````Enum.reduce(
enumerable,
initial_acc,
fn(element, acc) ->
...
end
)
``````

``````iex(5)> Enum.reduce(
...(5)>   [1,2,3],
...(5)>   0,
...(5)>   fn(element, sum) -> sum + element end
...(5)> )
6

iex(6)> Enum.reduce([1,2,3], 0, &+/2)
6
``````

``````defmodule NumHelper do
def sum_nums(enumberable) do
end

defp add_num(num, sum) when is_number(num), do: sum + num

end
``````

``````iex(8)> NumHelper.sum_nums([1,"Hi", :xyz, 2, 3, "World"])
6
``````

## List Comprehension

``````iex(9)> for x <- [1,2,3] do
...(9)>   x * x
...(9)> end
[1, 4, 9]
``````

Elixir有for,用在 List Comprehension,看上面的範例,就與一般程式語言

Erlang的List Comprehension格式偏向數學式,Elixir偏向一般方式.

``````[ x || x <- ListofIntegers, x > 0]
``````

``````customers = [
%{ name: "arale",    height: 1.39},
%{ name: "doraemon", height: 1.293},
%{ name: "godzilla", height: 150}
]

for data = %{ height: howtall} <- customers
howtall < 2
do: IO.inspect data
``````

``````%{height: 1.39, name: "arale"}
%{height: 1.293, name: "doraemon"}
``````