Body is a function block
Do ... end block is organized way of expression.
# ./times.exs下
defmodule Times do def doule(n) do n * 2 end end
And pattern-matching function calls
code show as below:
./ # factorial.exs computing class defmodule Factorial do DEF of (0), do: # 1 termination condition to write on it, otherwise it will never be enforced to the DEF of (the n-), do: the n-* of (the n-- 1 ) End
Sentinel clause
code show as below:
defmodule Guard do def what_is(x) when is_number(x) do IO.puts "#{x} is a number" end def what_is(x) when is_list(x) do IO.puts "#{x} is a list" end def what_is(x) when is_atom(x) do IO.puts "#{x} is an atom" end end
They assert immediately after the function is defined by one or more when keywords. When executed, the first execution based on matching parameters, and then evaluate all when assertions.
Sentinel clause does not support && and ||
The default parameters
When you define a function name, you can use param \\ value statement to specify default values for any parameter.
# ./default_param.exs defmodule Example do def func(p1, p2 \\ 2, p3 \\ 3, p4) do IO.inspect [p1, p2, p3, p4] end end Example.func("a", "b") #=> ["a", 2, 3, "b"] Example.func("a", "b", "c") #=> ["a", "b", 3, "c"] 从从左到右匹配 Example.func("a", "b", "c", "d")
There may receive the following error:
FUNC DEF (p1, P2 \\ 2, \\ 3 p3 , P4) DEF FUNC (p1, P2) # When the two arguments, calls can not be determined DEF FUNC (p1, P2 \\ 123 ) # pass two when the parameters can not be determined call
def func(p1, p2)
You can add a parameter contains default, and no function calls on all body functions, while the rest use common functions, those default values will be applied to this function only function header section
Part # omitted
DEF FUNC (P1, P2 \\ 123 ) DEF FUNC (P1, P2) When ... DEF FUNC (P1, P2) ...
|> Pipeline operator
|> The result left expression, which is passed to the right of the function call as the first parameter
people = DB.find_customers orders = Orders.for_customers(people) tax = sales_tax(orders, 2013) filing = prepare_filing(tax) #可以写为 filing = DB.find_customers |> Orders.for_customers |> sales_tax(2013) |> prepare_filing val |> f( a, b ) 等价于 f( val, a, b)
Module
Module provides a namespace for content definition. It can be used to encapsulate named functions, macros can also be encapsulated, structure, protocols, and other modules
Command module
Its scope in order to appear at the instruction as a starting point, until the end of the current scope
import