Skip to content

Instantly share code, notes, and snippets.

@majiang
Created May 22, 2012 13:45
Show Gist options
  • Save majiang/2769165 to your computer and use it in GitHub Desktop.
Save majiang/2769165 to your computer and use it in GitHub Desktop.
function style
module functionstyle;
import std.stdio;
T delegate(T) zero(T)(T delegate(T) f)
{
T ret(T x)
{
return x;
}
return &ret;
}
T delegate(T) delegate(T delegate(T)) succ(T)(T delegate(T) delegate(T delegate(T)) n)
{
T delegate(T) ret(T delegate(T) f)
{
T eval (T x)
{
return f(n(f)(x));
}
return &eval;
}
return &ret;
}
uint succ_uint(uint x)
{
return x+1;
}
T delegate(T) delegate_from_function(T) (T function(T) f)
{
T ret(T x)
{
return f(x);
}
return &ret;
}
void unit_test()
{
auto n = delegate_from_function(&zero!uint);
foreach (i; 0..10)
{
writefln("i = %d: f(0) = %d", i, n(delegate_from_function(&succ_uint))(0));
n = succ(n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment