Created
February 29, 2012 16:53
-
-
Save jsvnm/1942423 to your computer and use it in GitHub Desktop.
funcs that generate funcs that generate values. and things yield returning as enumerables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static public class FunFactory | |
{ | |
static public Func<TResult> Make<TResult>(TResult a, Func<TResult, TResult> step) | |
{ | |
TResult next=a; | |
return ()=>{ TResult cur=next; next=step(cur); return cur; }; | |
} | |
static public Func<TResult> Cycle<TResult>(IEnumerable<TResult> values) | |
{ | |
IEnumerator<TResult> it=values.GetEnumerator(); | |
return ()=>{ if(it.MoveNext() || (it=values.GetEnumerator()).MoveNext()) | |
return it.Current; | |
throw new System.InvalidOperationException("No next value");}; | |
} | |
static public Func<TResult> Cycle<TResult>(TResult[] values) | |
{ | |
int idx=-1; | |
return ()=>values[(idx = ++idx%values.Length)]; | |
} | |
static public Func<char> Cycle(char from, char to) { int n=from-1; return ()=>(char)(n=(++n>to)?from:n); } | |
static public Func<int> Cycle(int from, int to) { int n=from-1; return ()=> (n=(++n>to)?from:n); } | |
} | |
static public class Sequence | |
{ | |
public static IEnumerable<TResult> Generate<TResult>(TResult start, Func<TResult,TResult> step) | |
{ | |
for(TResult current = start; true; current = step(current)) | |
yield return current; | |
} | |
public static IEnumerable<TResult> Generate<TSeed, TResult>(TSeed start, Func<TSeed,TSeed> step, Func<TSeed,TResult> convert) | |
{ | |
for(TSeed current = start; true; current = step(current)) | |
yield return convert(current); | |
} | |
public static IEnumerable<char> Cycle(char a, char b) | |
{ | |
return Generate(a, (c => (char)(++c>b ? a : c))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment