本節深入探討函數式編程範式,對比命令式編程,揭示其核心特徵、優勢與局限,並以 Haskell、Groovy 實作快速排序為例。
public class Sorter {
public static <T extends Comparable<? super T>> void qsort(T[] list) {
qsort(list, 0, list.length - 1);
}
private static <T extends Comparable<? super T>> void qsort(T[] list, int low, int high) {
if (low >= high) return;
int i = low - 1, j = high + 1;
T pivot = list[low];
for (;;) {
do { ++i; } while (list[i].compareTo(pivot) < 0);
do { --j; } while (list[j].compareTo(pivot) > 0);
if (i >= j) break;
T tmp = list[i]; list[i] = list[j]; list[j] = tmp;
}
qsort(list, low, j);
qsort(list, j + 1, high);
}
}
核心:指定計算過程(賦值、迴圈、流程控制),屬過程式思維。
qsort :: (Ord a) => [a] -> [a]
qsort [] = []
qsort (pivot : rest) = qsort [x | x <- rest, x < pivot]
++ [pivot]
++ qsort [x | x <- rest, x >= pivot]
核心:聲明計算原則(遞歸分解),無賦值、無迴圈,極度精簡。
def qsort(list) {
if (list.size() <= 1) return list
def pivot = list[0]
return (qsort(list.findAll { x -> x < pivot })
+ list.findAll { x -> x == pivot }
+ qsort(list.findAll { x -> x > pivot }))
}
保留函數式核心,語法更親近 Java 開發者。
filter (< pivot) rest 中 (< pivot) 為高階函數。(pivot:rest) 解構、[x | x <- rest, x < pivot] 列表推導(對應數學集合表示法 {x | x ∈ rest, x < pivot})。| 優勢 | 局限 |
|---|---|
| 代碼簡潔、表達力強 | 思維模式偏數學抽象,學習曲線陡峭 |
| 天然支援並發與優化 | 語言表達力與執行效率在早期遜於命令式/OOP |
| 易於推理、測試、重構 | 大型系統工程化工具鏈相對較弱 |
| 領域特定語言(DSL)構建利器 | 非純函數語言(Lisp、ML)仍有副作用 |