I am trying to understand how to use case
command with variables in Scheme
(define CONSTANT 5)
(define x 5)
(case x ((CONSTANT) "equal") (else "not equal"))
The above example results in "not equal". Why?
Note that the following example works:
(define CONSTANT 5)
(define x 5)
(case x ((5) "equal") (else "not equal"))
If you look at the documentation, it's stated that:
The selected clause is the first one with a datum whose
quoted
form isequal?
to the result ofval-expr
.
The key word here is "quoted". The expression in the clause is not evaluated, is taken literally as it was written. So in fact you're trying to match against the symbol 'CONSTANT
. We can verify this:
(define x 'CONSTANT)
(case x
((CONSTANT) "equal")
(else "not equal"))
=> "equal"
UPDATE: From the comments, it appears that you need to match an element against a list of constants. A cond
+ member
will work better:
(define CONSTANT1 1)
(define CONSTANT2 2)
(define CONSTANT3 3)
(define x 3)
(define constants (list CONSTANT1 CONSTANT2 CONSTANT3))
(cond ((member x constants) "equal")
(else "not equal"))
=> "equal"