iex> if String.valid?("Hello") do
...> "Valid string!"
...> else
...> "Invalid string."
...> end
"Valid string!"
iex> if "a string value" do
...> "Truthy"
...> end
"Truthy"
unless/2 使用方法和 if/2 一样,不过只有当判断为否才会继续执行:
iex> unless is_integer("hello") do
...> "Not an Int"
...> end
"Not an Int"
case
如果需要匹配多个模式,我们可使用 case:
iex> case {:ok, "Hello World"} do
...> {:ok, result} -> result
...> {:error} -> "Uh oh!"
...> _ -> "Catch all"
...> end
"Hello World"
_ 变量是 case/ 语句重要的一项,如果没有 _,所有模式都无法匹配的时候会抛出异常:
iex> case :even do
...> :odd -> "Odd"
...> end
** (CaseClauseError) no case clause matching: :even
iex> case :even do
...> :odd -> "Odd"
...> _ -> "Not Odd"
...> end
"Not Odd"