[Prev][Next][Index][Thread]

Re: Closures



In article <3C0879DF.9030400@staffware-spokane.com>, 
dhockin@staffware-spokane.com wrote:

> I'm new to Dylan and functional programming.  I've been reading
> the DRM and "Dylan Programming".
> 
> The closures example in the DRM confuses me:
> 
> define method make-score (points :: <number>)
>    method (increase :: <number>)
>      points := points + increase;
>    end method;
> end method make-score;
> define constant score-david = make-score(100)
> define constant score-diane = make-score(400)
> score-david(0)
> fi 100
> score-david(10)
> fi 110
> score-david(10)
> fi 120
> score-diane(10)
> fi 410
> score-david(0)
> fi 120
> 
> I can follow creating new methods with different initial values
> of points.  But the methods seem to also have associated
> with them a persistent points slot, kind of like a
> C local static variable who's value keeps getting
> updated each time the method is called.

Right, but note that unlike a C static variable, each time you call 
"make-score" you get a new one.

The way you can think about this is that in Dylan nothing is stored on 
the stack, it's all on the heap, as with malloc() in C.  So the "points" 
variable doesn't get destroyed when make-score returns, but only when 
the last reference to it disappears, which doesn't happen until the last 
reference to the local function disappears -- which you might do by 
writing 'score-david := "something else"'.  Of course it would need to 
be a variable not a constant to do that.


Here's another example:

define method make-account(balance, interest-rate)
  values(
    method() balance end,
    method(amount) balance := balance + amount end,
    method() balance := balance + balance * interest-rate / 100.0 end
  )
end;

begin
  let (my-balance, my-deposit, my-calc-interest)
    = make-account(100, 3);
  my-deposit(50);
  my-calc-interest();
  my-balance();
end;

=> 154.5


> Somehow this seems to violate Dylan's separation of
> objects and functions.  The closure created function
> seems to have associated with it an object with slot
> points.  What am I missing?

In fact there is an isomorphism between closures and objects.  They are, 
at some level, the same thing.  In some non-OO languages (such as 
Scheme), closures are used to simulate objects.  In languages without 
closures, such as Java, objects are frequently used to simulate closures 
(e.g. anonymous classes in Java).

Objects and classes are used so frequently now that it's worth putting 
in specific language features to make them easier to use.  Especially 
since inheitance is tedious to simulate using closures.

-- Bruce



Follow-Ups: References: