[ create a new paste ] login | about

Link: http://codepad.org/jQVo3Rlt    [ raw code | output | fork | 1 comment ]

joshua_cheek - C, pasted on Nov 26:
#include <stdio.h>
#include <stdarg.h>

void say_hello( char* name ) 
{
  printf( "hello %s\n" , name );
  return;
}


//takes a named function, and calls it for each element in the array
//problems: must create function for every different way of calling this (pollutes namespace, dissassociates action from location)
//          needs to know too much information about the array (ie it is char** so can't pass int** or double** )
//          needs to know too much information about the function being called to handle it (ie it's return type, and type of params)
void for_each( char** array , int size , void (*action)( char* ) ) 
{
  int i;
  for( i=0 ; i<size ; ++i )  action(array[i]);
  return;
}


//can take any type, can receive and execute code, also executes in local environment
//problems: name conflicts, in this case, the local variable i is likely to conflict with some other code somewhere
//          so if they use i in their code, then they have a conflict 
//         ( my solution has been to obfuscate the variable name like this: i_akA90hv23 )
#define FOR_EACH( array , size , the_element , your_code ) \
{                                                          \
  int i;                                                   \
  for( i=0 ; i<size ; ++i )                                \
  {                                                        \
    the_element = array[i];                                \
    your_code;                                             \
  }                                                        \
}


int main( int argc , char const *argv[] ) {
  
  char *a[] = { "josh","gen","hoang" };

  //using function pointers
  for_each( a , 3 , say_hello ); 
  
  printf( "\n\n\n" );
  
  //same as the above, but macros make it feel like an anonymous function
  char* name;
  FOR_EACH( a , 3 , name ,
    printf( "hello %s\n" , name );
  )

  printf( "\n\n\n" );

  //using macros again, this shows that you can handle different types of arrays, and have local scope
  int b[] = { 1 , 2 , 3 };
  int the_int , sum=0;
  FOR_EACH( b , 3 , the_int ,
    sum += the_int;
    printf( "the int is %d , sum is %d\n" , the_int , sum );
  )
  
  return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
hello josh
hello gen
hello hoang



hello josh
hello gen
hello hoang



the int is 1 , sum is 1
the int is 2 , sum is 3
the int is 3 , sum is 6


Create a new paste based on this one


Comments:
posted by joshua_cheek on Nov 26
Shows how you can mimick ruby style lambdas.

This shows two ways to do mimic this Ruby code in C (macros are obviously my preference):

a = [ "josh" , "gen" , "hoang" ]

a.each do |name|
puts "hello #{name}"
end

reply