概要
paiza.ioでelixirやってみた。
cond,case,with使ってみた。
サンプルコード
{n, m} = {100, 150}
result =
cond do
n > 100 -> "n is big"
m > 100 -> "m is bigger"
true -> "n nor m is not so big"
end
|> IO.inspect
cond do
0 > 1 -> "No"
0 > 2 -> "Nope"
true -> "fallback"
end
|> IO.inspect
case {1, 0, 3} do
{1, x, 3} when x > 0 ->
"マッチする"
{1, x, 3} ->
"マッチする"
_ ->
"マッチしない"
end
|> IO.inspect
func = fn ->
"hello"
end
result =
case func.() do
str when is_nil(str) ->
"empty!"
str when is_binary(str) and str == "hello" ->
"yeah!"
_ ->
"oops!"
end
|> IO.inspect
case {1, 2, 3} do
{4, 5, 6} ->
"This clause won't match"
{1, x, 3} ->
"This will match and bind x to 2"
_ ->
"This will match any value"
end
|> IO.inspect
cond do
1 + 1 == 3 ->
"I will never be seen"
2 * 5 == 12 ->
"Me neither"
true ->
"But I will (this is essentially an else)"
end
|> IO.inspect
with {:ok, {int, _asdf}} <- Integer.parse("123asdf"), {:ok, datetime, _utc_offset} <- DateTime.from_iso8601("2021-10-27T12:00:00Z") do
DateTime.add(datetime, int, :second)
else
:error ->
"couldn't parse integer string"
{:error, :invalid_format} -> "couldn't parse date string"
_ ->
"this will never get hit because all errors are handled"
end
|> IO.inspect
try do
throw(:hello)
catch
message ->
"Got #{message}."
after
IO.puts("I'm the after clause.")
end
実行結果
"m is bigger"
"fallback"
"マッチする"
"yeah!"
"This will match and bind x to 2"
"But I will (this is essentially an else)"
"this will never get hit because all errors are handled"
I'm the after clause.
成果物
以上。