SICP_3.7-3.8
Posted lan126
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SICP_3.7-3.8相关的知识,希望对你有一定的参考价值。
第一次写的:
1 ;(define (make-account balance secret-password-list) 2 3 ; (define (withdraw amount) 4 ; (if (>= balance amount) 5 ; (begin (set! balance (- balance amount)) 6 ; balance) 7 ; "Insufficient funds")) 8 ; 9 ; (define (deposit amount) 10 ; (set! balance (+ balance amount)) 11 ; balance) 12 ; 13 ; (define (dispatch m) 14 ; (cond 15 ; ((eq? m ‘withdraw) withdraw) 16 ; ((eq? m ‘deposit) deposit) 17 ; (else (error "Unknow request -- MAKE-ACCOUNT" 18 ; m)))) 19 ; (lambda (p m) 20 ; (if (in? p secret-password-list) (dispatch m) 21 ; (lambda (x) "Incorrect password")))) 22 23 24 ;(define in? 25 ; (lambda (x list) 26 ; (cond ((null? list) #f) 27 ; ((eq? x (car list)) #t) 28 ; (else (in? x (cdr list)))))) 29 30 ;(define (make-joint account old-pa new-pa) 31 ; (set! account (make-account ((account (car old-pa) ‘withdraw) 0) 32 ; (cons new-pa old-pa))))
我尝试用建立列表的方法来做,但是这就导致了不同的账户可以用不同的密码来操作。
同时我写的这个过程还有bug,我用set!去 把一个新过程赋给一个旧过程,但是结果
上,Paul 可以通过 Peter 的密码来操作账户,Peter可以用Paul的来操作。可是,这两个
账户却是独立的,并没有关联起来,Paul对账户的操作,不会影响Peter账户,反之亦然。
所以set!到底做了什么,会出现这种情况?
换一个思路后:
1 (define (make-account balance secret-password) 2 3 (define (withdraw amount) 4 (if (>= balance amount) 5 (begin (set! balance (- balance amount)) 6 balance) 7 "Insufficient funds")) 8 9 (define (deposit amount) 10 (set! balance (+ balance amount)) 11 balance) 12 13 (define (dispatch m) 14 (cond 15 ((eq? m ‘withdraw) withdraw) 16 ((eq? m ‘deposit) deposit) 17 (else (error "Unknow request -- MAKE-ACCOUNT" 18 m)))) 19 (lambda (p m) 20 (if (eq? p secret-password) (dispatch m) 21 (lambda (x) "Incorrect password")))) 22 23 24 (define (make-joint account old-password new-password) 25 (lambda (password mode) 26 (if (eq? password new-password) 27 (account old-password mode) 28 "Incorrect password"))) 29 30 (define peter-acc (make-account 100 ‘open-sesame)) 31 32 (define paul-acc 33 (make-joint peter-acc ‘open-sesame ‘rosebud)) 34 35 ((paul-acc ‘rosebud ‘withdraw) 10) 36 ((peter-acc ‘open-sesame ‘withdraw) 20) 37 ((paul-acc ‘rosebud ‘deposit) 10) 38 ((peter-acc ‘rosehud ‘deposit) 10)
这个是在make-joint 过程中对密码进行判断,如果给的密码和新密码相同就通过旧密码去访问账户
不同的账户只能通过,自己的密码来访问账户
3.8:
1 (define f 2 (let ((called #f)) 3 (lambda (x) 4 (if called 5 0 6 (begin (set! called #t) 7 x))))) 8 9 (+ (f 1) (f 0)) 10 (+ (f 0) (f 1))
以上是关于SICP_3.7-3.8的主要内容,如果未能解决你的问题,请参考以下文章