Skip to content

Instantly share code, notes, and snippets.

@takoeight0821
Last active October 19, 2016 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takoeight0821/ad1d0133b530ce00c48f to your computer and use it in GitHub Desktop.
Save takoeight0821/ad1d0133b530ce00c48f to your computer and use it in GitHub Desktop.
C言語で多相もどきとmap
#include <stdio.h>
#define map(TYPE, SOURCE, RESULT, FUNC)\
TYPE RESULT[sizeof(SOURCE) / sizeof(SOURCE[0])] = {0};\
for (int i = 0; i < (sizeof(SOURCE) / sizeof(SOURCE[0])); i++) {\
RESULT[i] = FUNC(SOURCE[i]);\
}
int square(int n) {
return n * n;
}
double div_three(double n) {
return n / 3.0;
}
int main(void) {
int int_nums[] = {1, 2, 3, 4, 5};
map(int, int_nums, result_s, square);
for (int i = 0; i < 5; i++) {
printf("%d ", result_s[i]);
}
printf("\n");
double real_nums[] = {1.2, 2.3, 3.4, 4.5, 5.6};
map(double, real_nums, result_d, div_three);
for (int i = 0; i < 5; i++) {
printf("%f ", result_d[i]);
}
return 0;
}
/**
* $ ./map_func
* 1 4 9 16 25
* 0.400000 0.766667 1.133333 1.500000 1.866667
*/
@takoeight0821
Copy link
Author

これメモリ管理大丈夫なんか

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment