【SICP練習】152 練習4.8,sicp練習1524.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))))