Last active
August 18, 2024 17:45
-
-
Save yne/6dc8253f89e13dd63cd0c3a0192dd35c to your computer and use it in GitHub Desktop.
Lambda in C11 + Generic
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
#include <stdio.h> | |
#define fn(c) ({int _ c;_;}) | |
#define list(c) sizeof(c)/sizeof(*c),c | |
#define map(LIST, CB) _Generic( (CB), int(*)(int, int, int*): map_arr, int(*)(int): map_val)(LIST, CB) | |
int map_val(size_t total, int *array, int (*cb)(int)) { | |
for(int i = 0; i < total; i++) | |
array[i] = cb(array[i]); | |
} | |
int map_arr(size_t total, int *array, int (*cb)(int, int, int*)) { | |
for(int i = 0; i < total; i++) | |
array[i] = cb(array[i], i, array); | |
} | |
int forEach(size_t total, int *array, int (*cb)(int)) { | |
for(int i = 0; i < total; i++) | |
cb(array[i]); | |
} | |
int findIndex(size_t total, int *array, int (*cb)(int)) { | |
for(int i = 0; i < total; i++) | |
if(cb(array[i]))return i; | |
return -1; | |
} | |
int find(size_t total, int *array, int (*cb)(int)) { | |
for(int i = 0, res; i < total; i++) | |
if(cb(array[i]))return array[i]; | |
return -1; | |
} | |
int every(size_t total, int *array, int (*cb)(int)) { | |
for(int i = 0, res; i < total; i++) | |
if(!cb(array[i]))return 0; | |
return 1; | |
} | |
int main(){ | |
int fibo[11] = {0,1}; | |
map(list(fibo), fn((int val, int idx, int*lst){ return idx > 1 ? lst[idx-1] + lst[idx-2] : lst[idx]; })); | |
forEach(list(fibo), fn((int v){ printf("%d ", v); }));printf("\n"); | |
int is = every(list(fibo), fn((int v){ return v < 100; })); | |
printf("every value < 100 ? %s\n", is ? "true":"false"); | |
map(list(fibo), fn((int v){ return v*v; })); | |
forEach(list(fibo), fn((int v){ printf("%d ", v); }));printf("\n"); | |
int at = findIndex(list(fibo), fn((int v){ return v > 100; })); | |
int el = find(list(fibo), fn((int v){ return v > 100; })); | |
printf("v>100 (%i) at [%i]\n", el, at); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment