Can you use C function pointers like you'd use LISP lambda?by qbguy (no login)I know gcc supports nested functions, so I tried making a compose function in C. Does this work in general or is it just a coincidence that it works in this case? ============================ /* BEGIN C CODE */ #include <stdio.h> typedef int (*intfn)(int); /* This is supposed to create a new function that computes a(b(x)) */ intfn compose(intfn a, intfn b) { int foo(int x) { return a(b(x)); } return foo; } /* This is just a simple function that returns one more than its argument */ int oneplus(int x) { return ++x; } int main() { intfn twoplus; twoplus = compose(&oneplus, &oneplus); printf("%d\n", twoplus(2)); return 0; } /* END C CODE */ ================================ This is equivalent to the LISP (Scheme) code (define (compose f1 f2) (lambda (x) (f1 (f2 x)))) ((compose 1+ 1+) 2) ; => 4 Where 1+ is a function that returns one more than its argument. If 1+ is not in your Scheme implementation, it can be defined easily as (define 1+ (lambda (x) (+ 1 x))) |
| Response Title | Author and Date |
| * You'll have to wait until Artelius comes back from a vacation. | on Jul 3 |
| RE: Can you use C function pointers like you'd use LISP lambda? | on Jul 6 |
| I did the tests like you said, and there is indeed only one function created | qbguy on Jul 6 |
| Your code crashes on my machine, and here's why... | on Jul 7 |