zoukankan      html  css  js  c++  java
  • “foreach”(遍历功能)的C和Lisp实现

     寒假的时候学了一段时间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) )));【这一句是输入】

    下面是输出

    image

    再看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==4return 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); 
    }

    image

  • 相关阅读:
    LeetCode 109 Convert Sorted List to Binary Search Tree
    LeetCode 108 Convert Sorted Array to Binary Search Tree
    LeetCode 107. Binary Tree Level Order Traversal II
    LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
    LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
    LeetCode 103 Binary Tree Zigzag Level Order Traversal
    LeetCode 102. Binary Tree Level Order Traversal
    LeetCode 104. Maximum Depth of Binary Tree
    接口和多态性
    C# 编码规范
  • 原文地址:https://www.cnblogs.com/facingwaller/p/foreach_in_lisp_and_c.html
Copyright © 2011-2022 走看看