Reference

控制反转

实验1 C、Scheme、java实现回调

C函数指针

//op.c文件
typedef int (*How_op)( int, int); //函数指针的种类
int op(int a, int b, How_op how_op){ // call using function pointer
return 2* how_op (a, b); //2*运算暗示op函数体可以很复杂
}

//ood.h文件
//op.c用
typedef int (*How_op)( int, int); //函数指针的种类
int op(int a, int b, How_op how_op);

//上层模块,main.c文件
#include <stdio.h>
#include "ood.h"
int plus(int a,int b) {
return a+b;
}

void testCallback(void){
int d =op(2, 5, &plus);//
printf("%d",d); //输出2*(2+5)
}

int main(void){
testCallback();
return 0;
}

Scheme

;;;op.rkt
(define (op a b how-op)
( how-op a b) )

;;;上层模块,main.rkt
(load "op.rkt")
;;;define function plus
(define (plus a b )
(+ a b))
;;;Pass a Function as an Argument
(op 1 3 plus)
(op 2 3 (lambda(x y)(* x y)));;;Pass a lambda as an Argument

(op 1+2i 3-4i *)
(op (list 1 2 3) (list 4 5 6) append )

Java