# [Translation] Elixir Getting Started 8 Modules

elixir-lang.org 8 Modules

## 8 Module

``````iex> String.length "hello"
5
``````

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

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

## 8.1 编译

``````defmodule Math do
def sum(a, b) do
a + b
end
end
``````

``````elixirc math.ex
``````

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

Elixir 项目通常将代码组织到三个目录 :

• ebin - 编译成的字节码
• lib - elixir代码，后缀.ex
• test - 测试文件 ，后缀.exs

## 8.2 脚本模式

.exs 后缀的文件是Elixir 脚本文件，意思是以脚本的方式运行Elixir代码, 例如：创建`math.exs`文件

math.exs:

``````defmodule Math do
def sum(a, b) do
a + b
end
end

IO.puts to_string(Math.sum(1, 2))
``````

``````elixir math.exs
``````

## 8.3 函数

``````defmodule Math do
def sum(a, b) do
do_sum(a, b)
end

defp do_sum(a, b) do
a + b
end
end

Math.sum(1, 2)    #=> 3
Math.do_sum(1, 2) #=> ** (UndefinedFunctionError)
``````

``````defmodule Math do
def zero?(0) do
true
end

def zero?(x) when is_number(x) do
false
end
end

Math.zero?(0)  #=> true
Math.zero?(1)  #=> false

Math.zero?([1,2,3])
#=> ** (FunctionClauseError)
``````

## 8.4 函数捕获(Function capturing)

``````\$ iex math.exs
``````
``````iex> Math.zero?(0)
true
iex> fun = &Math.zero?/1
&Math.zero?/1
iex> is_function fun
true
iex> fun.(0)
true
``````

``````iex> &is_function/1
&:erlang.is_function/1
iex> (&is_function/1).(fun)
true
``````

``````iex> fun = &(&1 + 1)
#Function<6.71889879/1 in :erl_eval.expr/5>
iex> fun.(1)
2
``````

`&1` 表示传递到函数的第一个参数, `&(&1+1)` 展开就是 `fn x -> x + 1`，你可以在Kernel.SpecialForms了解更多`&` 相关

## 8.5 默认参数

Elixir也支持默认参数

``````defmodule Concat do
def join(a, b, sep // " ") do
a <> sep <> b
end
end

IO.puts Concat.join("Hello", "world")      #=> Hello world
IO.puts Concat.join("Hello", "world", "_") #=> Hello_world
``````

``````defmodule DefaultTest do
def dowork(x // IO.puts "hello") do
x
end
end
``````

``````iex> DefaultTest.dowork 123
123
iex> DefaultTest.dowork
hello
:ok
``````

``````defmodule Concat do
def join(a, b // nil, sep // " ")

def join(a, b, _sep) when nil?(b) do
a
end

def join(a, b, sep) do
a <> sep <> b
end
end

IO.puts Concat.join("Hello", "world")      #=> Hello world
IO.puts Concat.join("Hello", "world", "_") #=> Hello_world
IO.puts Concat.join("Hello")               #=> Hello
``````

``````defmodule Concat do
def join(a, b) do
IO.puts "***First join"
a <> b
end

def join(a, b, sep // " ") do
IO.puts "***Second join"
a <> sep <> b
end
end
``````

``````concat.ex:7: this clause cannot match because a previous clause at line 2 always matches
``````

``````\$ iex concat.ex
``````
``````iex> Concat.join "Hello", "world"
***First join
"Helloworld"
``````
``````iex> Concat.join "Hello", "world", "_"
***Second join
"Hello_world"
``````

Happy Hacking

11 人关注
63 篇文章