计算机程序的构造和解释 练习题3.4

将之前写的make-monitored过程添加进去,然后监视pass?谓词的调用次数,然后改造dispatch-password过程,当次数达到7次时,调用call-the-cops过程。

#lang racket
(define (make-account balance password)
  (define (withdraw amount)
    (if (>= balance amount)
        (begin (set! balance (- balance amount))
               balance)
        "Insufficient funds"))
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  
  (define (pass? p)
    (eq? p password))
  
  (define pass-monitor? (make-monitored pass?))
  
  (define (call-the-cops f)
   (displayln "call-the-cops"))
  
  (define (dispatch-password p m)
      (let ((is-pass (pass-monitor? p))
            (times (pass-monitor? 'how-many-calls?)))
        (cond (is-pass  (begin (pass-monitor? 'reset-count) (dispatch m)))
              ((>= times 7) call-the-cops)
              (else (lambda (x) "Insufficient password" )))))
  
  (define (dispatch m)
    (cond ((eq? m 'withdraw) withdraw)
          ((eq? m 'deposit) deposit)
          (else (error "Unknown request -- MAKE-ACCOUNT"
                       m))))
  dispatch-password)

(define (make-monitored f)
  (let ((times 0))
    (define (func m)
      (begin (set! times (+ times 1))
             (f m)))
    (define (monitor m)
      (cond ((eq? m 'how-many-calls?) times)
            ((eq? m 'reset-count) (set! times 0))
            (else (func m))))
    monitor))

(define acc (make-account 100 'secret-password))

((acc 'secret-password 'withdraw) 40)

((acc 'some-other-password 'deposit) 40)
((acc 'some-other-password 'deposit) 40)
((acc 'some-other-password 'deposit) 40)
((acc 'some-other-password 'deposit) 40)
((acc 'some-other-password 'deposit) 40)
((acc 'some-other-password 'deposit) 40)
((acc 'some-other-password 'deposit) 40)

运行结果

60
"Insufficient password"
"Insufficient password"
"Insufficient password"
"Insufficient password"
"Insufficient password"
"Insufficient password"
call-the-cops
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值