tags:

views:

108

answers:

3

Is there a way to check if a variable exists in Scheme? Even doing things like (if variable) or (null? variable) cause errors because the variable is not defined. Is there some function that returns whether or not a variable exists?

A: 

According to R6RS, it's a syntax violation to make a call to an unbound variable.

http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-12.html#node_sec_9.1

However, depending on your implementation there should be a way (theoretically, at least) to query the environment and check if a variable is a member. You'd need to do some further reading for that, however.

http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-17.html#node_idx_1268

Greg
+1  A: 

Here's an example in Racket:

#lang racket
(define x 1)
(define-namespace-anchor ns)
(define (is-bound? nm)
  (define r (gensym))
  (not (eq? r (namespace-variable-value nm #t
                                            (lambda () r) 
                                            (namespace-anchor->namespace ns)))))

(is-bound? 'x)
(is-bound? 'not-bound-here)
Sam TH
A: 

You want to ask questions to the environment. This is not possible with R5RS, and I'm not sure about R6RS. I certainly would like to do that using just the Scheme standard (and this may be part of R7RS -- look for "Environment enquiries" in the list of items they are likely going to work on).

As far as I can tell there are currently only ad-hoc solutions to that so you'll have to read your implementation's documentation.

Chicken supports that with the oblist egg (it lets you obtain a list of all interned symbols), and also with the environments egg, which lets you specificaly ask if one symbol is bound.

Depending on your implementation if may be possible to test this by making a reference to the variable and catching an exception, then checking if it was a not-bound exception, or something similar to that.

Jay