Answers
回答
1 Hello Elixir
2 Basic syntax
3 Pattern Match
Exercise 3-1
# xに1が、yに4が束縛されるようパターンマッチを完成させてください。
[0, x, 2, 3, y, 5] = [0, 1, 2, 3, 4, 5]
x == 1 and y == 4
true
Exercise 3-2
# 3を変数xに束縛
%{c: x} = %{a: 1, b: 2, c: 3}
x == 3
true
Exercise 3-3
# :aを変数x、2.3を変数yに拘束(1と"a"は何にも拘束しない)
[_, x, _, y] = [1, :a, "a", 2.3]
x == :a and y == 2.3
true
Exercise 3-4
# 2を変数x、4を変数y、5~10のリストをzに拘束(1と3は何にも拘束しない)
[1, x, 3, y | z] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x == 2 and y == 4 and z == [5, 6, 7, 8, 9, 10]
true
Exercise 3-5
# 1を変数x、4を変数yに拘束
%{a: %{b: x, d: [_, y, _]}} = %{a: %{b: 1, c: 2, d: [3, 4, 5]}}
x == 1 and y == 4
true
Exercise 3-6
# 複雑なパターンマッチを試してみよう
request = %{
header: %{
"x-custom-header": "a8d3981b2"
},
body: %{
first_name: "Alice",
last_name: "Liddell",
address: [
"Westminster",
"London",
"England",
"United Kingdom"
]
}
}
# requestのbodyからfirst_nameとlast_nameを同時に取り出してみよう
%{body: %{first_name: first_name, last_name: last_name}} = request
first_name == "Alice" and last_name == "Liddell"
true
Exercise 3-7
# requestのbodyのaddressは地区、州、構成国、主権国家の順に並んでいる。州(state)と構成国(country)だけ取り出してみよう
%{body: %{address: [_, state, country, _]}} = request
state == "London" and country == "England"
true
4 Function and module
Exercise 4-1
request = %{
header: %{content_type: "application/json"},
body: %{target: 21, message_to_you: "This may be the answer of everything."}
}
extract_answer = fn %{body: %{target: value}} -> value * 2 end
extract_answer.(request) == 42
true
Exercise 4-2
func = fn x, y, callback -> callback.(x, y) end
add = &(&1 + &2)
func.(1, 2, add) == 3
true
Exercise 4-3
# implement Name module!
defmodule Name do
def get_first_name(%{first_name: value}) do
value
end
def get_last_name(%{last_name: value}) do
value
end
def get_full_name(name_map) do
"#{get_first_name(name_map)} #{get_last_name(name_map)}"
end
end
name_map = %{first_name: "Jose", last_name: "Valim"}
Name.get_first_name(name_map) == "Jose" and
Name.get_last_name(name_map) == "Valim" and
Name.get_full_name(name_map) == "Jose Valim"
true
5 Control syntax
Exercise 5-1
response = %{status: 400, body: %{message: "Invalid parameter!"}}
result =
case response do
%{status: 200, body: body} -> {:ok, body}
%{status: 400} -> {:error, :bad_request}
%{status: 404} -> {:error, :not_found}
%{status: 500} -> {:error, :internal_error}
end
result == {:error, :bad_request}
true
6 pipe operator with Enum module
7 Use hex packages