views:

127

answers:

4

How to undefine a variable in Scheme? Is this possible?

+1  A: 

You cannot unbind a variable in standard Scheme. You could set! the variable to 'undefined, I guess, or you could write a metainterpreter which reifies environments, allowing you to introduce your own notion of undefining variables.

rak5hasa
+1  A: 

In Scheme, variables are defined with either lambda, or one of the various lets. If you want one of them to be 'undefined' then all you need to do is leave the scope that they're in. Of course, that's not really undefining them, it's just that the variable is no longer bound to its previous definition.

If you're making top level definitions, using (define), then technically you're defining a function. Since Scheme is functional, functions never really go away. I suppose that technically, it's stored in some sort of environment function somewhere, so if you were intimately familiar with your implementation (and it's not safeguarded somehow) you could probably overwrite it with your own definition of the globabl environment. Barring that, I'd say that your best bet would be to redefine the function to return the null list- that's really as empty as you get.

Greg
you could also do (set! x (display 'ignored)) because `display` returns "an unspecified value".
Nathan Sanders
You can define non-function values at the top level in Scheme, and locally bound functions do indeed "go away".
Anthony
Thanks for answer. I realized my question was something wrong :) I realized 'define' defines something in top-level scope, so it just remained until scope ends (program exit)
Eonil
+1  A: 
(set! no-longer-needed #f)

Does this achieve the effect you want? You can also use define at the top level.

guile> (define nigel "lead guitar")
guile> nigel
"lead guitar"
guile> (define nigel #f)
guile> nigel
#f
guile> 

You could then re-define the variable. This all depends on the scope of the variables, of course: see Greg's answer.

Joel J. Adamson
Just a note for Eonil: set! destroys referential transparency because it introduces side effects, and thus should be avoided if you want to stick to being purely functional.
Greg
A: 

I think, if your point is to do the equivalent of "free" or de-allocate, then no you're pretty much out of luck. you can't de-allocate a variable. you CAN re-define it to something small, like #f, but once you've done (define foo 'bar) the variable foo will exist in some form until you end the program.

On the other hand, if you use let, or letrec, of course, the name only exists until the relevant close paren...

Brian Postow
Thanks for answer. I realized it was just a scope problem :)
Eonil