1

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

(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 ()>。我的代码有什么问题?

4

1 回答 1

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
于 2013-06-06T21:33:04.980 回答