Instantly share code, notes, and snippets.

Embed
What would you like to do?
C11 Lambda + Generic
#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(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(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(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