zoukankan      html  css  js  c++  java
  • 【SICP练习】152 练习4.8

    练习4-8

    原文

    Exercise 4.8. “Named let” is a variant of let that has the form

    (let <var> <bindings> <body>)

    The and are just as in ordinary let, except that is bound within to a procedure whose body is and whose parameters are the variables in the . Thus, one can repeatedly execute the by invoking the procedure named . For example, the iterative Fibonacci procedure (section 1.2.2) can be rewritten using named let as follows:

    (define (fib n) 
       (let fib-iter ((a 1)    
                      (b 0)    
                      (count n))
          (if (= count 0)      
              b      
              (fib-iter (+ a b) a (- count 1)))))

    Modify let->combination of exercise 4.6 to also support named let.

    分析

    希望大家还是有事没事看看原文啦,我才发现见过非常多次的modify原来是改动的意思。

    关于named let的一些比較什么的,大家能够看这里:【Scheme归纳】3 比較do, let, loop

    从题目的代码中我们也能够看到named-let的名字能够用cadr来取出,也就是书中的fib-iter。而body部分从下面代码中也能够看出来得用3个cdr和1个car。

    (let <var> <bindings> <body>)

    而parameter题中已经说了是binding中变量。取出binding用caddr,而取出题目演示样例中的a、b和count等则用map和car就可以。取出题目演示样例中的1、0和n则用map和cadr。

    那么接下来我们还须要将named-let转换成函数,用list来构造这些就好,首先当然是’define。然后再用cons把name和parameter构造在一起,最后就是body啦。

    当然了,在let->combination中我们须要推断是不是named-let?。那么怎么推断呢。先推断是否是let?,再推断expr的名字是不是符号(symbol?)。

    最后就能够写let-combination啦。首先用写好的named-let?谓词来进行推断expr,然后为真的话就调用第257页的sequence->exp函数。否则就用cons来继续构造了。

    代码

    
    (define (named-let-name expr) 
      (cadr expr))
    
    (define (named-let-body expr)
      (cadddr expr))
    
    (define (named-let-parameters expr)
      (map car (caddr expr)))
    
    (define (named-let-exp expr)
      (map cadr (caddr expr)))
    
    (define (named-let? expr)
      (and (let? expr) (symbol? (cadr expr))))  
    
    (define (named-let->func expr)
      (list 'define
        (cons (named-let-name epxr)
              (named-let-parameters expr))
        (named-let-body expr)))
    
    (define (let->combination expr)
      (if (named-let? expr)
          (sequence->exp
           (list (named-let->func expr)
             (cons (named-let-name expr) 
               (named-let-exp expr))))
          (cons (make-lambda (let-vars expr)
                 (list (let-body expr)))
            (let-exp expr))))
    



    为使本文得到斧正和提问,转载请注明出处:
    http://blog.csdn.net/nomasp

  • 相关阅读:
    deepin-wine-tim 字体发虚
    windows&linux双系统时间相差8小时
    Linux 禁用 ipv6
    双系统win10更新后无法进入linux
    Failed to receive SOCKS4 connect request ack 解决
    zsh 使用通配符功能
    vux修改css样式的2种办法
    Ubuntu 16.04 安装OpenSSH7.4
    Nginx开启http2访问和gzip网页压缩功能
    vue开发环境和生产环境里面解决跨域的几种方法
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/6978229.html
Copyright © 2011-2022 走看看