unj2
unj2

Reputation: 53491

How do you define a constant in PLT Scheme?

How do I declare that a symbol will always stand for a particular value and cannot be changed throughout the execution of the program?

Upvotes: 5

Views: 4302

Answers (4)

Chris
Chris

Reputation: 3050

A really hackish answer that I thought of was to define a reader macro that returns your constant:

#lang racket
(current-readtable 
  (make-readtable (current-readtable)
                  #\k 'dispatch-macro (lambda (a b c d e f) 5)))

#k ;; <-- is read as 5

It would then be impossible to redefine this (without changing your reader macro):

(set! #k 6) ;; <-- error, 5 is not an identifier

Upvotes: 1

Eli Barzilay
Eli Barzilay

Reputation: 29556

In PLT Scheme, you write your definitions in your own module -- and if your own code is not using `set!', then the binding can never change. In fact, the compiler uses this to perform various optimizations, so this is not just a convention.

Upvotes: 5

Jay Kominek
Jay Kominek

Reputation: 8783

You could define a macro that evaluates to the constant, which would protect you against simple uses of set!

(define-syntax constant
  (syntax-rules () 
    ((_) 25)))

Then you just use (constant) everywhere, which is no more typing than *constant *

Upvotes: 3

Kyle Cronin
Kyle Cronin

Reputation: 79103

As far as I know, this isn't possible in Scheme. And, for all intents and purposes, it's not strictly necessary. Just define the value at the toplevel like a regular variable and then don't change it. To help you remember, you can adopt a convention for naming these kinds of constants - I've seen books where toplevel variables are defined with *stars* around their name.

In other languages, there is a danger that some library will override the definition you've created. However, Scheme's lexical scoping coupled with PLT's module system ensure this will never happen.

Upvotes: 10

Related Questions