How do you define a constant in a PLT diagram?

How to declare that a character will always stand for a specific value and cannot be changed during program execution?

+4
source share
4 answers

As far as I know, this is not possible in the Scheme. And, in all senses and purposes, this is not strictly necessary. Just define the value at the top level as a regular variable, and then do not change it. To help you remember, you can accept the naming convention for these types of constants - I saw books where top-level variables are defined with *stars* around their name.

In other languages, there is a risk that some library will override the definition you created. However, the Scheme lexical field in combination with the modular PLT system ensures that this never happens.

+8
source

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

+5
source

You can define a macro that evaluates to a constant that protects you from just using set!

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

Then you just use (constant) everywhere that no longer prints than * constant *

+2
source

The really hacky answer I was thinking about was to define a reader macro that returns your constant:

 #lang racket (current-readtable (make-readtable (current-readtable) #\k 'dispatch-macro (lambda (abcdef) 5))) #k ;; <-- is read as 5 

Then it would be impossible to override this (without changing your reader macro):

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

Source: https://habr.com/ru/post/1286653/


All Articles