我正在编写代码来模拟类:
(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 ()>
。我的代码出了什么问题?
答案 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