Advertisement
tyler569

Something resembling lambdas ish

Aug 8th, 2018
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.89 KB | None | 0 0
  1.  
  2. typedef unsigned long size_t;
  3. int printf(const char *fmt, ...);
  4.  
  5. typedef long (*func)();
  6.  
  7. typedef struct lambda {
  8.     func function;
  9.     void *captures[32];
  10. } lambda;
  11.  
  12. #define CAPTURE(...) __VA_ARGS__
  13. #define LAMBDA(name, captures, func...) func \
  14.     lambda name = { (void *)&lambda_function, captures }
  15.  
  16. #define lambda_ctx void **captures
  17. #define ctx(n, type) *(type *)captures[n]
  18.  
  19. #define lambda_call(lambda, args...) \
  20.     lambda.function(lambda.captures, args)
  21.  
  22.  
  23.  
  24. int foo() {
  25.     int x = 11, y = 100;
  26.     char *foo = "Hello World";
  27.  
  28.     LAMBDA( q,
  29.         CAPTURE({&x, &y, &foo}),
  30.         int lambda_function(lambda_ctx, int x) {
  31.             int a = 100;
  32.             int *p = &ctx(1, int);
  33.  
  34.             char *str = ctx(2, char *);
  35.             printf("%s\n", str);
  36.  
  37.             return a + ctx(0, int) + x;
  38.         }
  39.     );
  40.  
  41.     return (int)lambda_call(q, 20);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement