// closures in C# using System; using System.Collections.Generic; // type A -> B in C# is Func. // Func(A,B,C) is type (A,B) -> C (not curried). // Func is called a "delegate" in C#. // A function that returns void is called an Action: Action is A -> void /* // use inheritance to solve problem of the "transfer" method interface transaction {} using account = Func; class doubletrans : transaction { public Action f; public doubletrans(Action f) { this.f=f; } } class voidtrans : transaction { public Action f; public doubletrans(Action f) { this.f=f; } } class othertrans : transaction { public Action f; public doubletrans(Action f) { this.f=f; } } */ public class closures { // I , K and S combinators public static a I(a x) => x; // same as { return x; } public static Func K(a x) => (b y) => x; // a->b->a public static Func,Func> S(Func> x) => (y) => (z) => x(z)(y(z)); //(a->b->c)->(a->b)->a->c // accumulator static Func make_accumulator() { int x = 0; return y => { x +=y; return x; }; }//make_accumulator // bank accounts static Func> make_account(double init) { double balance = init; Action deposit = (double amt) => { if (amt>0) balance += amt; }; Action withdraw = (double amt) => { if (amt>0 && amt inquiry = (x) => { Console.WriteLine("your balance is "+balance); }; return (string request) => { switch (request) { case "withdraw" : return withdraw; case "deposit" : return deposit; case "inquiry" : return inquiry; default: return (x) => Console.WriteLine("invalid request"); }//switch }; }//make_account public static void Main() { var a1 = make_accumulator(); var a2 = make_accumulator(); Console.WriteLine(a1(2)); Console.WriteLine(a1(2)); Console.WriteLine(a1(2)); Console.WriteLine(a2(2)); var acc = make_account(200); acc("withdraw")(30); acc("deposit")(100); Action inquiry = () => acc("inquiry")(0); inquiry(); }//main }