// Lambda calculus in C (restricted to int basic types) // be sure to compile with genuine Gnu gcc #include #include #define Null 0 #define Bool int typedef int (*intfun)(int); // functions of type int->int typedef Bool(*intpred)(int); // predicates of type int->bool typedef int (*intop)(int,int); // binary operators typed int*int->bool int I (int x) { return x; } // lambda x.x as an intfun // wrong way to define K: int wrongK(int x, int y) { return x; } // right way to define K: intfun K(int x) { int inner(int y) { return x; } return inner; // return pointer to inner } intfun KI(int x) { // lambda x.lambda y.y int inner(int y) { return y; } return inner; } int main() { printf("(I 5): %d\n", I(5)); printf("((K 2) 4): %d\n", K(2)(4)); printf("((K 0) 1): %d\n", K(0)(1)); // apply K to just one argument intfun K1 = K(1); intfun K3 = K(3); printf("K(1)(4): %d\n", K1(4)); // this might print 3, why? printf("K(3)(4): %d\n", K3(4)); // might also get seg. fault // FAILURE! // C can take lambda args, but can't return lambdas with free vars // C cannot create a CLOSURE. //But KI is OK, why? intfun KI1 = KI(1), KI2 = KI(2); printf("KI(1)(2) is %d\n",KI1(2)); printf("KI(2)(4) is %d\n",KI2(4)); return 0; }//main