DAY 7
1
Software Development

## 匿名函式

Elixir 匿名函式最簡單的宣告語法如下：

``````foo = fn (x) -> x + 1 end
``````

``````is_odd = fn
x when is_integer(x) and rem(x, 2) == 1 -> true
_ -> false
end
``````

``````foo.(1)
#=> 2

is_odd.(4)
#=> false
``````

### 匿名函式的（偏差）行為

Elixir 刻意讓具名函式與匿名函式的語法有所區隔，因為它們有個很關鍵的行為差異：自由變數綁定

``````var a = 100;
function foo(b) {
return a + b;
}
var bar = function(b) {
return a + b;
}
var baz = b => a + b;
``````

``````defmodule Math do
a = 10
def foo(b) do
a + ｂ
end
end

#=> (CompileError) math.exs:6: undefined function a/0
``````

``````a = 100
foo = fn b -> a + b end
``````

``````foo = fn b -> a + b end
a = 100 # 太晚宣告了
``````

## 其它匿名函式規則

``````foo = fn i -> i * 10 end

[1, 2, 3]
|> Enum.max  # 具名函式不一定要加括號
|> fn i -> i + 1 end.()
|> foo.()
``````

``````Enum.map([1, 2, 3], fn i -> i + 1 end)
``````

## 重點回顧

• 匿名函式語法是 `fn x -> end`
• 匿名函式參數也是 pattern matching、也可以使用 guards，也可以有多個函式區塊
• 匿名函式會綁定外部變數
• 呼叫匿名函式要用 `.()` ，包括在 pipe 中使用時。

### 1 則留言

1

iT邦新手 5 級 ‧ 2017-12-26 23:41:23

taiansu iT邦新手 5 級 ‧ 2017-12-27 00:20:21 檢舉