Re: efficiency of let used in a binding

From: Bo Berghout <bo_at_drum.demos.su>
Date: Wed, 22 Oct 1997 15:32:17 +0400 (MSD)

>
> I just caught myself doing the following :
>
> (define (mouse-motion x y)
> (let ((new-x (transform x))
> (new-y (transform y)))
> ...))
>
> (bind drawing "<Motion>" mouse-motion)
>
>
> I don't understand how scheme allocates "local" variables. Is it a
> c-like thing where it's pushed on the stack and then popped or is the
> variable allocated and then when the routine returns the space must be
> gc'ed.
>

In my opinion, the Scheme way to solve this problem is to use
closures as in following listing:

(define mouse-motion
  (let ((my-x some-initial-value)
        (my-y some-initial-value) )
    (lambda (x y)
      (set! my-x (transform x))
      (set! my-y (transform y))
      .
      .
      .
      ... ) ))

Now, storage for my-x and my-y is allocated only once, and those cells
are not reachable out of mouse-motion body. Apropos, you also may write
a thread-safe version of program using following:

(define (make-mouse-motion-handler)
  (let ((my-x some-initial-value)
        (my-y some-initial-value) )
    (lambda (x y)
      (set! my-x (transform x))
      (set! my-y (transform y))
      .
      .
      .
      ... )) )

  Function make-mouse-motion-handler returns a closure with newly allocated
storage for my-x and my-y every time is called.

  Well, STklos is a closure-based object system, isn't it?

Good luck!
  Bo Berghout

===========================
Bo Berghout
mailto:bo_at_demos.su
http://www.ethereal.ru/~bo
===========================
Received on Wed Oct 22 1997 - 12:28:34 CEST

This archive was generated by hypermail 2.3.0 : Mon Jul 21 2014 - 19:38:59 CEST