在方案中模拟类

时间:2013-06-06 21:27:57

标签: scheme

我正在编写代码来模拟类:

(define (className)
  (define value 1)
  (define (obj arg1)                    ;constructor
    (define (increment)
      ((+ value 1)))
    (define (get)
      (value))
    (if (equal? arg1 "increment")
        (increment)
        (get)))
  obj)

(define a className)
(display a) ;returns #<procedure className ()>
(display (a "get")) ;trying to call get procedure

我正在ERROR: Wrong number of arguments to #<procedure className ()>。我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

存在一些问题 - 一些不必要的括号,一些缺少的括号以及increment过程并未真正改变value变量的事实。在这里,这应该解决它:

(define (className)
  (define value 1)
  (define (obj arg1)
    (define (increment)
      (set! value (+ value 1)))
    (define (get)
      value)
    (if (equal? arg1 "increment")
        (increment)
        (get)))
  obj)

让我们看看它是否有效:

(define a (className))

(display a)
=> #<procedure:obj>

(display (a "get"))
=> 1

(a "increment")
(display (a "get"))
=> 2