寒假的时候学了一段时间LISP,现在越来越发现其优雅漂亮,
比起命令式的少了许多繁琐。LISP的例子 取自我寒假的一道练习题,没有刻意意把功能做强大。
放出最近在做东西,顺便跟大家交流学习。
LISP版本
;定义了 foreach 这个函数
(define (foreach list action )
(if(null? list )
null
(cons (action (car list)) (foreach (cdr list) action ))
)
)
(display (foreach (list 1 2 3 4 5 ) (lambda (x) (* x x) )));【这一句是输入】
下面是输出
再看C语言的版本,这个是近期做的,功能比较强大,当然也就复杂一些,
主要是用来练习函数指针这个知识点和尝试运用函数指针实现抽象化。
C语言版本
/*
title:函数指针-实现foreach
create:2011年4月09日6:26下午
author:aqq
功能:myforeach 迭代实现容器
思路:
1 迭代器foreach(容器,迭代子, )
IN:满足某规则的容器 :void *cp=getNext();
OUT:遍历单个元素
2 拦截条件
3 执行方法
4 终止条件
update:2011年4月10日12:28下午
实现了foreach代码加入了END函数以判断是否该结束
*/
static int index = 0 ;
void myforeach( void * container
, void * ( * getnext)( void * )
, bool ( * Filter)( void * )
, void ( * Excute)( void * )
, bool ( * End)( void * )
){
void * next = ( * getnext)(container );
while ( ( * End)(next) ){
if ( ( * Filter)( next) ){ // 得到下一个
( * Excute)(next);
}
next = ( * getnext)(container );
}
}
void * Next( void * a ){
if (index == 4 ) return NULL;
else index ++ ;
int * n = ( int * )a;
printf( " \n now is %d \n " , * (n + index));
return (n + index);
}
bool Filter( void * a){
return true ;
}
bool End( void * a){
if (a == NULL) return false ;
// int *n=(int *)a;
// if(*n==NULL) return false;
return true ;
}
void Exc( void * number){
int * n = ( int * )number;
printf( " %d- is -ok-- " , * n );
}
void functionPointer_e2(){
int a[ 5 ] = { 0 , 1 , 2 , 3 , 4 };
void * p = a;
myforeach(p,Next,Filter,Exc,End);
}
title:函数指针-实现foreach
create:2011年4月09日6:26下午
author:aqq
功能:myforeach 迭代实现容器
思路:
1 迭代器foreach(容器,迭代子, )
IN:满足某规则的容器 :void *cp=getNext();
OUT:遍历单个元素
2 拦截条件
3 执行方法
4 终止条件
update:2011年4月10日12:28下午
实现了foreach代码加入了END函数以判断是否该结束
*/
static int index = 0 ;
void myforeach( void * container
, void * ( * getnext)( void * )
, bool ( * Filter)( void * )
, void ( * Excute)( void * )
, bool ( * End)( void * )
){
void * next = ( * getnext)(container );
while ( ( * End)(next) ){
if ( ( * Filter)( next) ){ // 得到下一个
( * Excute)(next);
}
next = ( * getnext)(container );
}
}
void * Next( void * a ){
if (index == 4 ) return NULL;
else index ++ ;
int * n = ( int * )a;
printf( " \n now is %d \n " , * (n + index));
return (n + index);
}
bool Filter( void * a){
return true ;
}
bool End( void * a){
if (a == NULL) return false ;
// int *n=(int *)a;
// if(*n==NULL) return false;
return true ;
}
void Exc( void * number){
int * n = ( int * )number;
printf( " %d- is -ok-- " , * n );
}
void functionPointer_e2(){
int a[ 5 ] = { 0 , 1 , 2 , 3 , 4 };
void * p = a;
myforeach(p,Next,Filter,Exc,End);
}