# Java 開發者的函數式程式設計（3）List 處理模式

English

``````sum [] = 0
sum (x:xs) = x + sum xs``````
Java 不支援模式匹配（Pattern match），我們可以使用 `if` 條件判斷來檢查清單物件是不是 `Nil`，因此可以如下定義一個 `sum` 方法：
``````public static Integer sum(List<Integer> lt) {
if(lt == Nil) return 0;
}``````

``````public static List<Integer> addOne(List<Integer> lt) {
if(lt == Nil) return nil();
}``````

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

``````public class AlgebraicType {
...
public static <T, R> List<R> map(List<T> lt, F1<T, R> f) {
if(lt == Nil) return nil();
}
}``````

``map(list(1, 2, 3, 4, 5), x -> x + 1);``

``map(list(1, 2, 3, 4, 5), x -> x - 2);``

``map(list(1, 2, 3, 4, 5), x -> x * 3);``

``````public static List<Integer> greaterThanThree(List<Integer> lt) {
if(lt == Nil) return nil();
else {
}
else {
return greaterThanThree(lt.tail());
}
}
}``````

``````public static List<Integer> smallerThanTen(List<Integer> lt) {
if(lt == Nil) return nil();
else {
}
else {
return smallerThanTen(lt.tail());
}
}
}``````

``````public class AlgebraicType {
...
public static <T> List<T> filter(List<T> lt, F1<T, Boolean> f) {
if(lt == Nil) return nil();
else {
}
else {
return filter(lt.tail(), f);
}
}
}
}``````

``filter(list(1, 2, 3, 4, 5), x -> x > 3);``

``filter(list(10, 19, 3, 4, 5), x -> x < 10);``

``````public interface F2 {
R apply(R r, P p);
}``````

``````public class AlgebraicType {
...
public static <T, R> R reduce(List<T> lt, F2<T, R> f, R r) {
if(lt == Nil) return r;
else {
}
}
}``````

``reduce(list(1, 2, 3, 4, 5), (sum, x) -> sum + x, 0);``