## C#函數式編程之序列

### 用函數方法實現迭代器

` 1         public static IEnumerable<T> Sequence<T>(Func<T, T> getNext, T startVal, Func<T, bool> endReached) 2         { 3             if (getNext == null) 4                 yield break; 5             yield return startVal; 6             T val = startVal; 7             while (endReached == null || !endReached(val)) 8             { 9                 val = getNext(val);10                 yield return val;11             }12         }`

`        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();        }`

### 值域

` 1         public class Range<T> : IEnumerable<T> 2         { 3             private T start; 4             private T end; 5             private Comparison<T> compare; 6             private IEnumerable<T> sequence; 7  8             private static int Compare<U>(U one,U other) 9             {10                 return Comparer<U>.Default.Compare(one,other);11             }12 13             public Range(T start, T end, Func<T, T> getNext, Comparison<T> compare)14             {15                 this.start = start;16                 this.end = end;17                 this.compare = compare;18                 this.sequence = Sequence<T>(getNext, start, v => compare(getNext(v), end) > 0);19             }20 21             public Range(T start, T end, Func<T, T> getNext)22                 : this(start, end, getNext, Compare) { }23 24             public IEnumerator<T> GetEnumerator()25             {26                 return sequence.GetEnumerator();27             }28 29             System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()30             {31                 return ((IEnumerable<T>)this).GetEnumerator();32             }33 34             public bool Contains(T value)35             {36                 return compare(value, start) >= 0 && compare(end, value) >= 0;37             }38         }`

### 限制

`1 foreach(int x in CFunc(10,TFunc)){2     Console.WriteLine(x);3 }`

至此關於函數式編程中的序列就結束了，后面的時間筆者將會抓緊時間盡快將這個專輯結束掉，開始集中在Xamarin.Android這個系列的教程上。

#### 注意！

© 2014-2020 ITdaan.com