The problem with closures

2 views
Skip to first unread message

JohanAR

unread,
Mar 10, 2010, 2:02:32 AM3/10/10
to proglang-course-2010
I'm really getting frustrated with closures now. We finished lab 4
some time with substitutions, but I thought it would be fun to do it
with closures too. However, basically all I've got about them is 2
slides showing their respective judgements so I think it's difficult
to find out how to implement them.

Using Xavier Leroy's slides I think I managed to implement call-by-
value using closures, by doing like this:

Value = Closure | Integer

When I evaluate (fun arg) I first evaluate arg to argV. Then I
evaluate fun to (Closure env' (Abstraction x body)). After that I
modify env' so that x := argV and finally evaluate (body arg) in the
latest environment.

Because I need to put (argV : Value) in the environment/closure, I
felt that I had to make the environment a map from Ident to Value
(instead of Expression) which might or might not be correct.

Either way it passes all tests except good2.fun which loops until
there's a stack overflow.


So the real problem is that I now want to convert it to call-by-name
instead.

If I don't evaluate arg to argV, it will be an expression. Should I
change the environment back to map Ident Expression? If I do that, I
don't really need to know how to handle Idents..
If I look up an Ident x which maps to Expression body and I evaluate
body it breaks the closures and I can't use the same variable name in
several functions. If I don't evaluate the body I have to do something
else with it so it becomes a Value, but trying to enclose it breaks
just about everything.

I'm also a little uncertain about the first method being a real call-
by-value, as many times arg will just evaluate to a Closure which is
then inserted into the body.

JohanAR

unread,
Mar 10, 2010, 4:01:16 AM3/10/10
to proglang-course-2010
Finally found the problem (with a little hint from some guy on the
Internet)..

The Environment should remain map Ident Value. When I look up an Ident
that maps to a Closure I should evaluate the body in the closure's
environment (I think I tried to do it in the current env). When I
apply (fun arg) I just stick arg Expression in a Closure with the
current environment.
And with that solved, it was pretty trivial to turn it into call-by-
need.


Suppose the next challenge is to modify the code so it uses StateT
instead of passing Environment. Managed to do it with our solution
that used substitutions, but I think this one will be more difficult
because some changes to environments should be discarded while other
ones saved.


Ah well, good luck on the exam tomorrow to everybody!

Reply all
Reply to author
Forward
0 new messages