概要
Elixirの対話モードで条件(case/cond/if)の動作を確認してみました。以下のページを参考にしました。
対話モードで実行
以下のコマンドを実行しました。
$ iex
Erlang/OTP 24 [erts-12.2.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [jit]
Interactive Elixir (1.12.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> case {:ok, "hello world"} do
...(1)> {:ok, result} -> result
...(1)> {:error, error} -> error
...(1)> _ -> "others"
...(1)> end
"hello world"
iex(2)> case rem(1, 2) do
...(2)> 0 -> :even
...(2)> end
** (CaseClauseError) no case clause matching: 1
iex(2)> case rem(1, 2) do
...(2)> 0 -> :even
...(2)> 1 -> :odd
...(2)> _ -> :oddity
...(2)> end
:odd
iex(3)> x = 1
1
iex(4)> case 2 do
...(4)> ^x -> 1
...(4)> x -> x
...(4)> end
2
iex(5)> x
1
iex(6)> case 3 do
...(6)> 1 -> :one
...(6)> 2 -> :two
...(6)> n when is_integer(n) and n > 2 -> :larger_than_two
...(6)> _ -> :not_integer
...(6)> end
:larger_than_two
iex(7)> is_even? = fn
...(7)> n when rem(n, 2) == 0 -> true
...(7)> n when rem(n, 2) == 1 -> false
...(7)> _ -> :not_integer
...(7)> end
#Function<44.65746770/1 in :erl_eval.expr/5>
iex(8)> is_even?.(1)
false
iex(9)> is_even?.(2)
true
iex(10)> is_even?.(2.0)
:not_integer
iex(11)> rem(2.0, 2)
** (ArithmeticError) bad argument in arithmetic expression: rem(2.0, 2)
:erlang.rem(2.0, 2)
iex(11)> case func = fn
...(11)> x -> x
...(11)> x, y -> x + y
...(11)> end
** (CompileError) iex:11: undefined function case/1
iex(11)> cond do
...(11)> 1 > 2 -> false
...(11)> is_integer(1.0) -> false
...(11)> nil -> false
...(11)> [1, 2, 3] -> true
...(11)> true -> "実行されない"
...(11)> end
true
iex(12)> cond do
...(12)> 1 == 2 -> false
...(12)> end
** (CondClauseError) no cond clause evaluated to a truthy value
iex(12)> if true do
...(12)> "実行される"
...(12)> end
"実行される"
iex(13)> if !0 do
...(13)> true
...(13)> else
...(13)> false
...(13)> end
false
iex(14)> unless 0 do
...(14)> "実行されない"
...(14)> end
nil
iex(15)> if(0 < 1, do: 1 + 2)
3
iex(16)> if(false, do: :this, else: :that)
:that
iex(17)> if(false, [do: :this, else: :that])
:that
iex(18)> if(true, do: (
...(18)> x = 2
...(18)> x * x
...(18)> ))
4
iex(19)> if true do
...(19)> x = 2
...(19)> x * x
...(19)> end
4
iex(20)> is_number if true do
...(20)> x = 2
...(20)> end
** (CompileError) iex:20: undefined function is_number/2
iex(20)> is_number(
...(20)> if true do
...(20)> x = 2
...(20)> end
...(20)> )
warning: variable "x" is unused (there is a variable with the same name in the context, use the pin operator (^) to match on it or prefix this variable with underscore if it is not meant to be used)
iex:22
true
iex(21)>
まとめ
何かの役に立てばと。