庄周梦蝶

生活、程序、未来
   :: 首页 ::  ::  :: 聚合  :: 管理

sicp 3.1.1小节习题尝试解答

Posted on 2007-07-24 17:12 dennis 阅读(262) 评论(0)  编辑  收藏 所属分类: 计算机科学与基础
    这一节主要是介绍局部状态变量,介绍了set!和begin的语法,看来ruby使用!号来表示改变变量值不是什么新鲜主意。
  
习题3.1,不解释了
;习题3.1
(define (make-accumulator init)
  (define (accumulator num)
    (set! init (+ init num))
    init)
  accumulator)

习题3.2,非常有趣的例子,在内部维持一个计数的变量即可,如果传入的参数是特定的符号就返回计数或者清0,如果不是,原过程调用。

;习题3.2
(define (make-monitored proc)
   (let ((counter 0))
  (define (proc-monitor args)
         (cond ((eq? args 'how-many-calls?) counter)
            ((eq? args 'reset-count) (begin (set! counter 0) counter))
            (else
              (begin (set! counter (+ counter 1)) (proc args)))))
  proc-monitor))

请注意,我的实现只能针对有一个参数的过程,对于多个参数的过程我还不知道怎么做。

习题3.3,passwd的局部状态变量,在dispatch前比较下传入的密码是否与之一致

;习题3.3
(define (make-account balance passwd)
  (define (withdraw amount)
    (if (>= balance amount)
        (begin (set! balance (- balance amount)) balance)
        "余额不足"))
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  (define (dispatch pwd m)
    (if (eq? pwd passwd)
        (cond ((eq? m 'withdraw) withdraw)
              ((eq? m 'deposit) deposit)
            (else
               (error "Unknow request--MAKE-ACCOUNT" m)))
        (lambda(x) "Incorrect password")))
        
  dispatch)
不一致的时候,返回一个匿名过程,仅仅是输出消息Incorrect password

习题3.4,在内部维持一个局部变量counter,用于计数密码错误的次数,在dispatch前判断counter是否等于7,如果是7就调用过程call-the-cops。

;习题3.4
(define (make-account balance passwd)
  (let ((counter 0))
  (define (withdraw amount)
    (if (>= balance amount)
        (begin (set! balance (- balance amount)) balance)
        "余额不足"))
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  (define (call-the-cops amount)
    "您已经尝试输入密码7次了!不能再试!")
  (define (dispatch pwd m)
    (cond ((= 7 counter) call-the-cops)
          ((eq? pwd passwd)
           (cond ((eq? m 'withdraw) withdraw)
                 ((eq? m 'deposit) deposit)
                 (else
                   (error "Unknow request--MAKE-ACCOUNT" m))))
          (else
            (begin (set! counter (+ counter 1)) (lambda(x) "Incorrect password")))))
 dispatch))





只有注册用户登录后才能发表评论。


网站导航: