[Haskell-cafe] Functions are first class values in C

Cristian Baboi cristian.baboi at gmail.com
Sat Dec 22 06:11:45 EST 2007


Let me show you an example to prove it.
The example is limited to composition of unary functions defined on int
    u::Int->Int
    v::Int->Int
    o ::(Int->Int)->(Int->Int)->(Int->Int)
    o u v= \x->u(v(x))


#include <stdio.h>
#include <conio.h>

#include "functional.h"

int f1(int x){
	return x+x;
}
int f2(int x){
	return 2*x;
}
int g1(int x){
	return x+1;
}
int g2(int x){
	return x-1;
}

#define P1 P0 int main(){
#define P2 P1      printf("%d,%d,%d\n",2,
#define P3           O(f1,f2,P2)(2),
#define	P4	     O(g1,g2,P3)(3));
#define P5 P4      getch();
#define P6 P5 }

MAIN P6


Here is the file functional.h

#define FUNC2(x,y) x##y
#define FUNC1(x,y) FUNC2(x,y)
#define FUNC(x) FUNC1(x,__COUNTER__)

#define COMP(c,f,g,p) \
	 int c (int x) { return f(g(x)); }; \
	 p \
	 c

#define O(f,g,p)  COMP( FUNC(a), f, g, p)

#define P0
#define MAIN



More information about the Haskell-Cafe mailing list