Elixir Modules
概要
Elixir の Modules について
Module の定義
defmodule で Module を定義します。
サンプルコード
defmodule Hoge do
def hoge(msg) do
msg
end
end
IO.puts Hoge.hoge("hoge")
出力
$ elixir modules.exs
hoge
名前付き関数の定義
def で 名前付き関数 を定義します。
サンプルコード
defmodule Hoge do
def hoge(msg) do
msg
end
end
IO.puts Hoge.hoge("hoge")
出力
$ elixir modules.exs
hoge
private な名前付き関数
defp で private な関数を作成します
サンプルコード
defmodule Hoge do
def hoge(msg) do
show_message(msg)
end
defp show_message(msg) do
msg
end
end
IO.puts Hoge.hoge("hoge")
関数定義の複数句、ガード句
Elixir では multiple clauses / guards を利用可能です。
サンプルコード
defmodule Num do
def print_year_or_aha(x) do
IO.puts yeah?(x)
end
defp yeah?(true) do
"year!"
end
defp yeah?(x) when is_boolean(x) do
"aha"
end
end
Num.print_year_or_aha(true)
Num.print_year_or_aha(false)
Num.print_year_or_aha("not boolean")
出力
$ elixir modules_multiple_guards.exs
year!
aha
** (FunctionClauseError) no function clause matching in Num.yeah?/1
/home/vagrant/samples/8/modules_multiple_guards.exs:6: Num.yeah?("not boolean")
/home/vagrant/samples/8/modules_multiple_guards.exs:3: Num.print_year_or_aha/1
src/elixir_compiler.erl:66: :elixir_compiler."-eval_forms/4-fun-0-"/7
src/elixir_compiler.erl:65: :elixir_compiler.eval_forms/4
src/elixir_compiler.erl:33: :elixir_compiler.quoted/2
/builddir/build/BUILD/elixir-0.8.3/lib/elixir/lib/code.ex:240: Code.require_file/2
/builddir/build/BUILD/elixir-0.8.3/lib/elixir/lib/kernel/cli.ex:282: Kernel.CLI.process_command/2
/builddir/build/BUILD/elixir-0.8.3/lib/elixir/lib/enum.ex:636: Enum."-map/2-lc$^0/1-0-"/2
関数のキャプチャ
&モジュール.関数/引数
の書式で関数のキャプチャが可能。
iex> String.downcase("HoGe")
"hoge"
iex> dm = &String.downcase/1
iex> dm.("HoGe")
"hoge"
参照