elixir 模块

时间:2024-09-01 23:36:32

模块定义  defmodule

函数定义  def

私有函数  defp  --相当于其他语言 private

iex(29)> defmodule Math do
...(29)> def sum(a, b) do
...(29)> a + b
...(29)> end
...(29)> end

iex(30)> Math.sum(1, 2)
3

捕捉语法 定义函数的快捷方式

iex(31)> fun = &(&1+1)
#Function<6.90072148/1 in :erl_eval.expr/5>
iex(32)> fun.(2)
3

等价于

iex(33)> a = fn x -> x + 1 end
#Function<6.90072148/1 in :erl_eval.expr/5>
iex(34)> a.(2)
3

默认参数

iex(38)> defmodule Concat do
...(38)> def join(a, b, sep \\ " ") do
...(38)> a <> sep <> b
...(38)> end
...(38)> end

iex(39)> IO.puts Concat.join("hello", "word")
hello word
:ok
iex(40)> IO.puts Concat.join("hello", "word", " ")
hello word
:ok