Hi guys.
Below ive written a foldl program which calculates the values in the array with the function add with values in the array from left to right. This is the non-polymorphic function with integers and a function add.
Code:
#include <stdio.h>
int add( int, int );
int foldl( int [], int, int (int,int) );
int main()
{
int a[3] = { 1, 2, 3 };
int ans;
ans = foldl( a, 3, add );
printf( "%d\n", ans );
return 0;
}
int add( int a, int b )
{
return (a+b);
}
int foldl( int a[], int size, int f( int a, int b) )
{
int i;
int ans;
ans=a[0];
for ( i=1; i<size; i++ )
{
ans = f( ans, a[i] );
}
return ans;
}
My question is, how can i turn this into a polymorphic program, i.e. using any type? I have trouble visualising the input to the function pointer f which the foldl calls.
At the moment foldl calls the add function. How can i pass an argument to a function pointer which allows me to manipulate the values.
for example the array {1,2,3} ..... and suppose the random function is (a*b)+(b/a). How can i pass "(a*b)+(b/a)" to the function f? or any random function f for that matter with two variables a and b?
if i put a+b then f function should be adding the values in the array. But how can i store this function or argument?
Code:
#include <stdio.h>
(void * ) f( (void *), (void *) );
(void * ) foldl( (void *) [], int, (void *) ((void *),(void *)) );
int main()
{
int a[3] = { 1, 2, 3 };
int ans;
ans = foldl( a, 3, a+b );
printf( "%d\n", ans );
return 0;
}
(void *) f( (void *) a, (void *) b )
{
return (a+b);
}
(void *) foldl( (void *) a[], int size, (void *) f( (void *) a, (void *) b) )
{
int i;
int ans;
ans=a[0];
for ( i=1; i<size; i++ )
{
ans = f( ans, a[i] );
}
return ans;
}