# 認識 Lambda/Closure（6）一級函式與 Lambda 演算

English

``λ x. x * 2``

``x -> x * 2``

``````(x -> x * 2)(2)
= 2 * 2
= 4``````

``````h(x)
= g(f(x))
= f(x) - 1
= x * 2 - 1``````

``````(y -> y - 1)(x -> x * 2)
= x -> x * 2 - 1``````

``````(x, y) -> x * x + y * y
= x -> (y -> x * x + y * y)``````
`a` 套用至 `x`，接著將 `b` 套用至 `y` 的話，則會是：
``````(x -> (y -> x * x + y * y))(a)(b)
= (y -> a * a + y * y)(b)
= a * a + b * b``````

``````let not =
* false -> true
* true -> false

let and =
* false value -> false
* true value -> value
* value false -> false
* value true -> value

let or =
* false value -> value
* true value -> true
* value false -> value
* value true -> true

let if = cond -> tv -> fv -> (cond and tv) or (not cond and fv)``````

``````if(true)(a)(b)
= ((cond or fv) and (cond and tv))(true)(a)(b)
=((true and tv) or (not true and fv))(a)(b)
=((true and a) or (not true and fv))(b)
=(true and a) or (not true and b)
= a or (false and b)
= a or false
= a``````

``let unless = cond -> fv -> tv -> (cond or fv) and (cond and tv)``
`unless` 函式在 `cond``true` 時會傳回第二個 `tv`。例如：
``````unless(true)(a)(b)
= ((cond or fv) and (cond and tv))(true)(a)(b)
= ((true or fv) and (true and tv))(a)(b)
= ((true or a) and (true and tv))(b)
= (true or a) and (true and b)
= true and b
= b``````

``````function(x) {
return x * 2;
};``````

``````public interface Func<P, R> {
R apply(P p);
}``````

``````new Func<Integer, Integer>() {
public Integer apply(Integer x) {
return x * 2;
}
};``````

``````public static <A, B, C> Func<A, C> compose(final Func<A, B> f, final Func<B, C> g) {
return new Func<A, C>() {
public C apply(A x) {
return g.apply(f.apply(x));
}
};
}``````

``````compose(
new Func<Integer, Integer>() {
public Integer apply(Integer x) {
return x + 2;
}
},
new Func<Integer, Integer>() {
public Integer apply(Integer y) {
return y * 3;
}
}
);``````