Skip to content

Instantly share code, notes, and snippets.

@sekrasoft
Created April 3, 2016 16:20
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 sekrasoft/9a66b67c856b9104df01dfa0580e96fe to your computer and use it in GitHub Desktop.
Save sekrasoft/9a66b67c856b9104df01dfa0580e96fe to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef double number;
typedef number* numbers;
typedef size_t index;
typedef number (*function)(number);
numbers map(function f, numbers xs, size_t size) {
numbers ys = malloc(size * sizeof(number));
if(!ys) return 0;
for(index i=0; i<size; ++i) ys[i] = f(xs[i]);
return ys;
}
number sqr(number x) {
return x*x;
}
int main(void) {
number nats[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
numbers squares = map(sqr, nats, 10);
if(squares) {
printf("squares: ");
for(int i=0; i<10; ++i)
printf("%.0f ", squares[i]);
free(squares);
} else {
printf("Sorry! No memory.");
}
return 0;
}
@sekrasoft
Copy link
Author

Вывод программы:

squares: 1 4 9 16 25 36 49 64 81 100 

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