Skip to content

Instantly share code, notes, and snippets.

@Luiz-Monad
Created November 20, 2017 23:34
Show Gist options
  • Save Luiz-Monad/a500f80b1f75f1325e3c8ea8b8edfe01 to your computer and use it in GitHub Desktop.
Save Luiz-Monad/a500f80b1f75f1325e3c8ea8b8edfe01 to your computer and use it in GitHub Desktop.
csharp recursive fixpoint
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace t1
{
static class Program
{
static void Main(string[] args)
{
var v = new List<int>();
for (var i = 0; i < 10; i++) v.Add(i);
Console.WriteLine();
var csum = Curry<int[], int, int>(Sum);
var fix = Uncurry(IFix(csum));
var r = fix(v.ToArray(), 0);
Console.WriteLine(r);
Console.ReadKey();
}
static int Sum(Func<int[], int, int> fix, int[] array, int index)
{
if (index >= array.Length) return 0;
return fix(array, index + 1) + 1;
}
static Func<I, O> Fix<I, O>(Func<Func<I, O>, Func<I, O>> f)
{
//Y f = f ( Y f )
return x => f(Fix(f))(x);
}
static Func<Func<Tuple<I1, I2>, O>, Func<Tuple<I1, I2>, O>> Curry<I1, I2, O>(Func<Func<I1, I2, O>, I1, I2, O> f)
{
return y => i => f(Uncurry(y), i.Item1, i.Item2);
}
static Func<I1, I2, O> Uncurry<I1, I2, O>(Func<Tuple<I1, I2>, O> f)
{
return (t1, t2) => f(Tuple.Create(t1, t2));
}
static Func<I, O> IFix<I, O>(Func<Func<I, O>, Func<I, O>> f)
{
return x =>
{
//f(Fix(f))(x);
I got = default(I);
var called = true;
Func<I, O> next = i =>
{
got = i;
called = true;
return default(O);
};
var ret = f(next)(x);
while (called)
{
called = false;
ret = f(next)(got);
}
return default(O);
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment