Skip to content

Instantly share code, notes, and snippets.

@jsvnm
Created February 29, 2012 16:53
Show Gist options
  • Save jsvnm/1942423 to your computer and use it in GitHub Desktop.
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
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