LoginSignup
0
0

More than 5 years have passed since last update.

Elixir Functions with Guard Clauses

Posted at

Elixir Functions with Guard Clauses

概要

Elixir の Functions と Guard Clauses について。

Function の呼び出し時に、引数の型によって処理を分けたい場合、
Guard Clauses を利用します。

サンプル

defmodule MultiModuleDouble do
  def double(x) when is_number(x) do
    x * 2
  end

  def double(x) when is_list(x) do
    x ++ x
  end

  def double(x) when is_binary(x) do
    try do
      double(String.to_integer(x))
    rescue
      e in ArgumentError -> x <> x
    end
  end
end

IO.inspect MultiModuleDouble.double(2)
IO.inspect MultiModuleDouble.double([1, 2, 3])
IO.inspect MultiModuleDouble.double("2")
IO.inspect MultiModuleDouble.double("a")
  • 出力
4
[1, 2, 3, 1, 2, 3]
4
"aa"
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0