拖了很久的函數式編程系列終於可以繼續。這段時間忙著把 Objective-C 教材改寫成 Swift 版,又花十幾天完成一個 Xamarin App 專案。回歸正題,這篇要談的是如何用函數式手法實作列表推導。
所謂列表推導,重點在於「列表的資料不是事先寫死的,而是依演算法即時算出來的」:程式啟動時並不計算,而是在被使用時才計算,而且只算到目前需要的那一項為止。這正是惰性求值(lazy evaluation)的精髓。
public static IEnumerable<T> Sequence<T>(Func<T, T> getNext, T startVal, Func<T, bool> endReached)
{
if (getNext == null)
yield break;
yield return startVal;
T val = startVal;
while (endReached == null || !endReached(val))
{
val = getNext(val);
yield return val;
}
}
這個函數依演算法反覆迭代:startVal 是起點,getNext 負責算出下一個值,endReached 決定何時停止。若 endReached 傳 null,序列就是無限的——但因為用了 C# 2.0 才有的 yield return,它並不會變成死迴圈,而是取到哪裡算到哪裡。
static void Main(string[] args)
{
var oddNumbersForm1 = Sequence<int>(x => x + 2, 1, x => x >= 20);
foreach (int x in oddNumbersForm1)
Console.WriteLine(x);
Console.ReadKey();
}
單靠 Sequence 表達「某個值是否落在範圍內」這類需求會很吃力,因此再包一層 Range,內部仍复用 Sequence:
public class Range<T> : IEnumerable<T>
{
private T start;
private T end;
private Comparison<T> compare;
private IEnumerable<T> sequence;
private static int Compare<U>(U one, U other)
{
return Comparer<U>.Default.Compare(one, other);
}
public Range(T start, T end, Func<T, T> getNext, Comparison<T> compare)
{
this.start = start;
this.end = end;
this.compare = compare;
this.sequence = Sequence<T>(getNext, start, v => compare(getNext(v), end) > 0);
}
public Range(T start, T end, Func<T, T> getNext)
: this(start, end, getNext, Compare) { }
public IEnumerator<T> GetEnumerator()
{
return sequence.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
public bool Contains(T value)
{
return compare(value, start) >= 0 && compare(end, value) >= 0;
}
}
Range 不但能產生序列,還提供 Contains 判斷某值是否在值域內,同時因為實作了 IEnumerable,就能免費取得 LINQ 的各種擴充方法。
如果迭代器本身就很複雜,再塞入限制條件會同時拖累效能與可讀性。更好的做法是把兩件事拆開:負責產生序列的函數不含任何限制,限制則移到外層。例如 TFunc 是無限制地回傳序列,CFunc 接受一個上限與產生函數,回傳套用條件後的序列:
foreach (int x in CFunc(10, TFunc))
{
Console.WriteLine(x);
}
關於函數式編程中的序列,就談到這裡。