简体   繁体   中英

Scheme - using `this` as argument of a lambda function?

Could someone please clarify the concepts behind this use of the "this" keyword?

(define call
  (lambda (obj method-name . args)
    (apply (obj method-name) obj args)))
(define -cuboid-
  (lambda (w l h)
    (define volume
      (lambda (this)
        (* h (call this 'area))))
    (define area
      (lambda (this)
        (* w l)))
    (lambda (method-name)
      (cond
        ((eq? 'volume method-name) volume)
        ((eq? 'area method-name) area)
        (else (error "method not found: ~s" method-name)))) 
(define r1 (-cuboid- 2 3 4))
(call r1 'area) ;=> 6
(call r1 'volume) ;=> 24

I understand that this is a keyword to refer to the object that is being used. I found out that this alone doesn't have any particular meaning in this program (it needs to refer to the arguments of the lambda functions).

The call is ((-cuboid- 2 3 4) 'volume) , which brings to (* h (call this 'area)) , where has this been defined?

this is simply the argument of the lambda , this could be anything; try changing it to, eg, myself in the first lambda and me in the second (where it is not used, by the way, but needs to be there for the call to work).

The call to ((-cuboid- 2 3 4) 'volume) returns that procedure, with names bound according to the sketch below:

In call , r1 'volume calls the "lookup method" of -cuboid- and returns the volume procedure, which is then called with the obj argument, binding that to the name this

Thus, this gets bound to the r1 argument to call

装订草图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM