Skip to content

Instantly share code, notes, and snippets.

@Warwolt
Last active January 11, 2020 20:47
Show Gist options
  • Save Warwolt/5cb8533c937008ed54bf3e2dce77d9df to your computer and use it in GitHub Desktop.
Save Warwolt/5cb8533c937008ed54bf3e2dce77d9df to your computer and use it in GitHub Desktop.
Example usage of closure header in C
/**
* A tiny language experiment, defining closures in C.
* The reference python-code that is implemented:
*
* def add(a):
* return (lambda b: a + b)
*
* def main():
* c = add(5)
* print('c(10) =', c(10))
*/
#include <stdio.h>
#include "closure.h"
/* Type definitions */
DEFINE_CLOSURE_TYPE(int, add, int); // closure from int arg to int return value
/* Function definitions */
DEFINE_CLOSURE_ENVIRONMENT_1(add, int); // closure captures one int argument
DEFINE_CLOSURE_BLOCK(int, add, int b) // defines returned functions behaviour
{
ENV_ARG_0(int, a); // access captured arg from environment
return a + b;
}
int main()
{
CLOSURE(add) c = add(5); // call capture function and store returned closure
printf("c(10) = %d\n", CALL_LOCAL_CLOSURE(c, 10)); // call closure
FREE_LOCAL_CLOSURE(c); // manually free
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment