【SICP练习】107 练习3.8
練習3-8
原文
Exercise 3.8. When we defined the evaluation model in section 1.1.3, we said that the first step in evaluating an expression is to evaluate its subexpressions. But we never specified the order in which the subexpressions should be evaluated (e.g., left to right or right to left). When we introduce assignment, the order in which the arguments to a procedure are evaluated can make a difference to the result. Define a simple procedure f such that evaluating
(+ (f 0) (f 1))will return 0 if the arguments to + are evaluated from left to right but will return 1 if the arguments are evaluated from right to left.
分析
題目中已經說明了求解一個表達式的第一步就是求值其中的子表達式,而對于
(+ (f 0) (f 1))意味著分別求解(f 0)和(f 1),可以猜測著其中有2個lambda表達式。又因為從左往右和從右往左的求值結果不同,則意味著2個lambda是嵌套的關系。
代碼
(define f(lambda (first-value)(set! f (lambda (second-valua) 0))first-value)) ;Value:測試
(define f(lambda (first-value)(set! f (lambda (second-valua) 0))first-value)) ;Value: f(+ (f 0) (f 1)) ;Value: 1(+ (f 1) (f 0)) ;Value: 0總結
當我們調用(f n)時,n為實參將會代替第四行的first-value,并進一步傳入第二行的lambda表達式。返回的結果則是n,但與此同時又將
(lambda (second-value) 0)賦值給過程f。而當下一次調用(f m)時,不論m為何值,都會返回0。也就是說第一次傳入的n,(f n)返回值為n,以后傳入的m,(f m)返回0,并且無論傳入多少次m,返回值均為0。當然了,m的值并未改變。
(f 1) ;Value: 1(f 1) ;Value: 0(f 1) ;Value: 0(f 1) ;Value: 0(define m 2) ;Value: m(f m) ;Value: 0m ;Value: 2同時也可以得出結論,MIT-Scheme對子表達式的求值順序是從右至左。
練習3-7
原文
Exercise 3.7. Consider the bank account objects created by make-account, with the password modification described in exercise 3.3. Suppose that our banking system requires the ability to make joint accounts. Define a procedure make-joint that accomplishes this. Make-joint should take three arguments. The first is a password-protected account. The second argument must match the password with which the account was defined in order for the make-joint operation to proceed. The third argument is a new password. Make-joint is to create an additional access to the original account using the new password. For example, if peter-acc is a bank account with password open-sesame, then
(define paul-acc (make-joint peter-acc 'open-sesame 'rosebud))will allow one to make transactions on peter-acc using the name paul-acc and the password rosebud. You may wish to modify your solution to exercise 3.3 to accommodate this new feature.
分析
make-joint需要有3個參數:
1.有密碼保護的帳戶名
2.必須與賬號的密碼匹配的原密碼
3.新密碼
而其會返回一個過程,因此在此處需要一個lambda表達式,并且其有一個參數mode和一個傳入的密碼參數。另外在輸出錯誤信息的函數中也需要一個參數,即是它并不使用,只是出于兼容性的考慮,在前面的博客中我們也遇到過這種問題。
代碼
(define (make-joint origin-acc old-password new-password)(define (display-wrong-message msg)(display "Incorrect password"))(lambda (given-password mode)(if (eq? given-password new-password)(origin-acc old-password mode)display-wrong-message))) ;Value: make-joint感謝訪問,希望對您有所幫助。 歡迎關注或收藏、評論或點贊。
為使本文得到斧正和提問,轉載請注明出處:
http://blog.csdn.net/nomasp
版權聲明:本文為 NoMasp柯于旺 原創文章,如需轉載請聯系本人。
轉載于:https://www.cnblogs.com/NoMasp/p/4786098.html
總結
以上是生活随笔為你收集整理的【SICP练习】107 练习3.8的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BZOJ2494 Triangles a
- 下一篇: TCP,IP,HTTP,SOCKET区别