Skip to content

Instantly share code, notes, and snippets.

@felipegtx
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipegtx/8933528 to your computer and use it in GitHub Desktop.
Save felipegtx/8933528 to your computer and use it in GitHub Desktop.
Monads in C#
public class Program
{
static Func<int> Identity(int x)
{
return () => x;
}
static Func<int, Func<int>> Multiply(Func<int> what)
{
return y => () => what() * y;
}
static Func<int, Func<int>> Divide(Func<int> what)
{
return y => () => what() / y;
}
static Func<int, Func<int>> Subtract(Func<int> what)
{
return y => () => what() - y;
}
static void Main(string[] args)
{
var eq = Divide(Multiply(Identity(2))(10))(4);
var res = eq();
Console.WriteLine(res);
}
}
public class Program
{
static void Main(string[] args)
{
Wrap(Wrap(Wrap(DoX)(DoY))(DoZ))(DoW)();
}
public static Func<Action, Action> Wrap(Action what)
{
Action<Action> run = t => { try { t(); } catch (Exception e) { Console.WriteLine(e.ToString()); } };
return whatElse => () =>
{
run(what);
run(whatElse);
};
}
public static void DoX()
{
Console.WriteLine("x");
}
public static void DoY()
{
Console.WriteLine("y");
}
public static void DoZ()
{
throw new Exception("Z");
}
public static void DoW()
{
Console.WriteLine("w");
}
}
public class Program
{
static Func<Func<T, T>, Func<T, T>> WrapIt<T>(Func<T, T> what)
{
Func<Func<T, T>, T, T> run = (f, x) =>
{
try { return f(x); }
catch (Exception e) { Console.WriteLine(e.ToString()); return default(T); }
};
return whatElse => x =>
{
return run(whatElse, run(what, x));
};
}
static double Quadrado(double i)
{
return Math.Pow(i, 2.0);
}
static double Cubo(double i)
{
return Math.Pow(i, 3.0);
}
static double Print(double i)
{
Console.WriteLine(i);
return i;
}
static void Main(string[] args)
{
var f = WrapIt(WrapIt(WrapIt<double>(Quadrado)(Print))(Cubo))(Print);
f(2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment