DAY 8
1

# Lambda表達式

Lambda Expression，又稱為匿名函式，可以用非常簡短的方式定義函式，也不用為函式命名。

``````x -> x^2 + 2x - 1
(x -> x^2 + 2x - 1)(5)  # 34
``````

``````f = x -> x^2 + 2x - 1
f(5)
``````

# 神奇的Map

``````a = x -> x^2
map(a, [1, 2, 3, 4])  # [1, 4, 9, 16]
``````

``````map(a, Set([1, 2, 3, 4]))  # Set([4,9,16,1])
``````

``````map(x -> Pair(string(x[1]), x[2]), Dict([1=>1, 2=>2, 3=>3]))
``````

# 好用的Filter

``````filter(x -> x < 5, [1, 3, 5, 7])  # [1, 3]
``````

``````u = map(x -> x^2, [1, 2, 3, 4, 5])
v = filter(x -> x < 10, u)
v
``````

# 巧妙的Reduce

``````x = 1 + 2 + 3 + 4 + 5
``````

``````x = (((1 + 2) + 3) + 4) + 5
``````

`reduce`他會幫你把前兩個先執行一次運算，接著將這個結果跟下一個元素一起運算，直到沒有元素為止。

``````reduce(+, [1, 2, 3, 4, 5])  # 15
``````

## Reduce的應用

`reduce`可以幫我們做很多事情，像是蒐集迴圈的計算結果。

``````f = x -> x^2 - 2
a = map(f, [1, 2, 3, 4, 5])  # 迴圈中的運算
b = reduce(push!, [], a)  # 蒐集結果
b
``````

``````g = (x, y) -> (isempty(x))? ((y, ), ): (x[end][1] == y)? (x[1:end-1]..., (x[end]..., y)) : (x..., (y, ))
c = reduce(g, (), [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4])
``````

``````((1,1,1),(2,2,2,2),(3,3,3,3,3,3),(4,))
``````

Julia語言—從入門到專案31