Created
July 9, 2015 03:23
-
-
Save ikouchiha47/0d4da5b92e3a75fd9b29 to your computer and use it in GitHub Desktop.
Functional programming with c , integer types
This file contains hidden or 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> | |
#include<stdlib.h> | |
#define arrlen(x) (sizeof(x)/sizeof((x)[0])) | |
int callback( int i ) { | |
return i * 2; | |
} | |
int callback_filter( int i ) { | |
return i % 2 == 0; | |
} | |
void print_R( int i ) { | |
printf("%d, ", i); | |
} | |
int* map( int src[], size_t count, int(*cb)(int) ) { | |
int i; | |
int *dest; | |
dest = (int *) calloc( count, sizeof( int ) ); | |
for( i = 0; i < count; i++ ) { | |
dest[ i ] = (*cb)(src[ i ]); | |
} | |
return dest; | |
} | |
int* filter( int src[], size_t count, int(*cb)(int) ) { | |
int i; | |
int c = 0; | |
int *dest; | |
dest = (int *) calloc( count, sizeof( int ) ); | |
for( i = 0; i < count; i++ ) { | |
if( (*cb)(src[ i ] ) > 0) { | |
dest[ c ] = src [ i ]; | |
++c; | |
} | |
} | |
return dest; | |
} | |
int* each( int *src, size_t count, void(*cb)(int)) { | |
int i; | |
for(i = 0; i < count; i++) { | |
(*cb)(src[ i ]); | |
} | |
return src; | |
} | |
int main( ) { | |
int array[9] = {1,2,3,4,5,6,7,8,9}; | |
int *result; | |
int i; | |
size_t len = arrlen( array ); | |
result = map( array, len, callback ); | |
each( result, len, print_R); | |
free(result); | |
printf("\n"); | |
result = filter( array, len, callback_filter ); | |
each( result, len, print_R); | |
free(result); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment