我正在看编程入门课程的一些其他练习,这是关于使用Scheme进行OOP的部分。
我将-circle-定义为具有参数半径的对象。另外,我将区域定义为-circle-的方法。
(define -circle-
(lambda (r)
(define area (lambda () (* pi r r)))
(lambda (method-name)
(cond
((eq? method-name 'area) area)
(else (error '-circle- "Method not found: ~s" method-name))
))))
我将调用定义为将可选参数应用于对象方法的函数。(我对这里的语法不是很在意,但这是给定的,我认为我的意思是:“首先将方法应用于对象,如果有参数,也将其放入”)。
(define call
(lambda (obj method-name . args)
(apply (obj method-name) args)))
测试示例(完全在DrRacket / Pretty Big中工作)是:
(define c1 (-circle- 3))
(call c1 'area)
但正如我所见,这种关闭将带来:
(call -circle- 3 'area)
代替:
(call -circle- 'area . 3)
(进而导致illegal use of '.'
错误)。
有人可以澄清在这种情况下带有可选参数的输入实际上是如何工作的吗?
您应该知道的第一件事是,点符号将零个或多个项目绑定到该点后的名称列表中。
(define (exmaple a b .c) c)
(example 1 2 3 4 5) --> (3 4 5)
其次,定义arent的文字,除非您使用文字。当您将y定义为y时,y会在与x关联之前进行求值。C1不是'(-circle- 3)
它用参数3评估-circle-的结果,这是(lambda (method-name) ...)
一个环境中的函数,其中称为radius的变量为3。
因此(call c1 'area)
,要评估的((lambda (method-name) ...) 'area)
是半径为3的位置。它返回(lambda () (* pi r r))
半径为3的位置。Apply然后将该函数应用于null列表(由于该函数没有形式参数,因此它很合适),该结果返回9 * pi的结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句