Created
November 10, 2010 16:28
-
-
Save DmitrySoshnikov/671072 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// lambda lifting (http://en.wikipedia.org/wiki/Lambda_lifting) | |
// in GNU C; use inner functions which are not closures | |
// of course, but have access to free variables | |
// | |
// by Dmitry A. Soshnikov | |
#include <stdio.h> | |
// a pointer to a function type | |
typedef int (*funcPtr)(int); | |
int foo(int x) | |
{ | |
int firstInner(int y) | |
{ | |
return x + y; | |
} | |
return firstInner(3); | |
} | |
funcPtr bar(int x) | |
{ | |
int secondInner(int y) | |
{ | |
return x + y; | |
} | |
// return the function | |
return secondInner; | |
} | |
int main() | |
{ | |
printf("%d\n", foo(2)); // OK, 5 | |
// returned function | |
funcPtr f1 = bar(3); | |
printf("%d\n", f1(2)); // also OK, 5 | |
// however, it's not a closure of course | |
// but just lambda lifting; | |
// an attemt to call it again with | |
// different arg will cause that the | |
// first one will return a new result also | |
funcPtr f2 = bar(5); | |
printf("%d\n", f2(2)); // OK, 7 | |
// see that we have the same function | |
printf("first: %p, second: %p\n", f1, f2); | |
// call the fist one again | |
printf("%d\n", f1(2)); // segmentation fault | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
out: