I typed this code in Dr Racket running on Linux Mint:
lang racket
(define x 2)
(define x 3)
and it shows me this:
module: duplicate definiton for identifier in: x
What should I do to be able to redefine a variable?
(Initially my code was longer but even only this part alone generates error)
In Racket define is used to declare a variable and at the same time set it to a value. To set the variable to a new value, use set!.
#lang racket
(define x 2)
(set! x 3)
x
Related
I'm new to Racket and there's something about syntax macros I don't understand. I have these two programs:
This one, which executes correctly:
#lang racket
(define-syntax-rule (create name) (define name 2))
(create x)
(displayln (+ x 3))
And this one, which complains that the identifier x is unbound:
#lang racket
(define-syntax-rule (create) (define x 2))
(create)
(displayln (+ x 3))
With a naive substitution approach (such as C/C++ macros) these two programs would behave identically, but evidently they do not. It seems that identifiers that appear in the invocation of a syntax macro are somehow "special" and defines that use them behave differently to defines that do not. Additionally, there is the struct syntax macro in the Racket standard library which defines several variables that are not explicitly named in its invocation, for example:
(struct employee (first-name last-name))
Will define employee? and employee-first-name, neither of which were directly named in the invocation.
What is going on here, and it can be worked around so that I could create a custom version of struct?
The problem with the naive substitution is unintentional capturing. Racket macros by default are hygienic, which means it avoid this problem. See https://en.wikipedia.org/wiki/Hygienic_macro for more details.
That being said, the macro system supports unhygienic macros too. struct is an example of an unhygienic macro. But you need to put a bit more effort to get unhygienic macros working.
For example, your second version of create could be written as follows:
#lang racket
(require syntax/parse/define)
(define-syntax-parse-rule (create)
#:with x (datum->syntax this-syntax 'x)
(define x 2))
(create)
(displayln (+ x 3))
Usually, I avoid using mutations since you rarely need them.
However, I need them and I am trying to understand better somethings. There is a specific behavior that intrigues me and I would like to ask for your help to understand it better.
If I type on the REPL the change bellow everything works:
> (define x 1)
> (set! x (+ x 1))
> x
2
If I put the assignment and the mutation on the definition window it also works:
(define y 1)
y
(set! y (+ y 1))
y
After running the file, I can see on the REPL the following correct result:
1
2
>
However, if I put the definition of variable x on the definition windows and if I try to set! it to a new value on the REPL I get an error:
; Definition Window
(define y 1)
;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;
; REPL
> (set! y (+ y 1))
. . y: cannot modify a constant
Why does that happen?
Shouldn't interactive programming be used especially for situations like this?
Thanks in advance.
According to Matthias Felleisen, one of the main responsible for the development of Racket so far:
The DrRacket REPL allows set!s on those variables that are assignable in the module and no others. That's by design. Roughly speaking, think of the Definitions window as a module and the REPL a way to perform computations as if we were a client of the module that can also use all of its internally defined functions, think super-client. But this super-client view does not enable you to mutate variables that weren't mutable in the first place .. just like a client can't do that either.
This information was presented in Racket's Mail list 7 years ago as pointed out in a comment of my own question in the post above.
I read a relevant post on binding, however still have questions.
Here are the following examples I found. Can someone tell me if the conclusions are correct?
Dynamic Binding of x in (i):
(defun j ()
(let ((x 1))
(i)))
(defun i ()
(+ x x))
> (j)
2
Lexical Binding of x in i2:
(defun i2 (x)
(+ x x))
(defun k ()
(let ((x 1))
(i2 2)))
> (k)
4
No Global Lexical Variables in ANSI CL so Dynamic Binding is performed:
(setq x 3)
(defun z () x)
> (let ((x 4)) (z))
4
Dynamic Binding, which appears to bind to a lexically scoped variable:
(defvar x 1)
(defun f (x) (g 2))
(defun g (y) (+ x y))
> (f 5)
7
Based on the above tests, CL first tries lexical binding. If there is no lexical match in the environment, then CL tries dynamic binding. It appears that any previously lexically scoped variables become available to dynamic binding. Is this correct? If not, what is the behavior?
(defun j ()
(let ((x 1))
(i)))
(defun i ()
(+ x x))
> (j)
2
This is actually undefined behavior in Common Lisp. The exact consequences of using undefined variables (here in function i) is not defined in the standard.
CL-USER 75 > (defun j ()
(let ((x 1))
(i)))
J
CL-USER 76 > (defun i ()
(+ x x))
I
CL-USER 77 > (j)
Error: The variable X is unbound.
1 (continue) Try evaluating X again.
2 Return the value of :X instead.
3 Specify a value to use this time instead of evaluating X.
4 Specify a value to set X to.
5 (abort) Return to top loop level 0.
Type :b for backtrace or :c <option number> to proceed.
Type :bug-form "<subject>" for a bug report template or :? for other options.
CL-USER 78 : 1 >
As you see, the Lisp interpreter (!) complains at runtime.
Now:
(setq x 3)
SETQ sets an undefined variable. That's also not fully defined in the standard. Most compilers will complain:
LispWorks
;;;*** Warning in (TOP-LEVEL-FORM 1): X assumed special in SETQ
; (TOP-LEVEL-FORM 1)
;; Processing Cross Reference Information
;;; Compilation finished with 1 warning, 0 errors, 0 notes.
or SBCL
; in: SETQ X
; (SETQ X 1)
;
; caught WARNING:
; undefined variable: COMMON-LISP-USER::X
;
; compilation unit finished
; Undefined variable:
; X
; caught 1 WARNING condition
(defvar x 1)
(defun f (x) (g 2))
(defun g (y) (+ x y))
> (f 5)
7
Dynamic Binding, which appears to bind to a lexically scoped variable
No, x is globally defined to be special by DEFVAR. Thus f creates a dynamic binding for x and the value of x in the function g is looked up in the dynamic environment.
Basic rules for the developer
never use undefined variables
when using special variables always put * around them, so that it is always visible when using them, that dynamic binding&lookup is being used. This also makes sure that one does NOT declare variables by accident globally as special. One (defvar x 42) and x will from then on always be a special variable using dynamic binding. This is usually not what is wanted and it may lead to hard to debug errors.
In summary: no, CL never 'tries one kind of binding then another': rather it establishes what kind of binding is in effect, at compile time, and refers to that. Further, variable bindings and references are always lexical unless there is a special declaration in effect, in which case they are dynamic. The only time when it is not lexically apparent whether there is a special declaration in effect is for global special declarations, usually performed via defvar / defparameter, which may not be visible (for instance they could be in other source files).
There are two good reasons it decides about binding like this:
firstly it means that a human reading the code can (except possibly in the case of a global special declaration which is not visible) know what sort of binding is in use – getting a surprise about whether a variable reference is to a dynamic or lexical binding of that variable is seldom a pleasant experience;
secondly it means that good compilation is possible – unless the compiler can know what a variable's binding type is, it can never compile good code for references to that variable, and this is particularly the case for lexical bindings with definite extent where variable references can often be compiled entirely away.
An important aside: always use a visually-distinct way of writing variables which have global special declarations. So never say anything like (defvar x ...): the language does not forbid this but it's just catastrophically misleading when reading code, as this is the exact case where a special declaration is often not visible to the person reading the code. Further, use *...* for global specials like the global specials defined by the language and like everyone else does. I often use %...% for nonglobal specials but there is no best practice for this that I know of. It's fine (and there are plenty of examples defined by the language) to use unadorned names for constants since these may not be bound.
The detailed examples and answers below assume:
Common Lisp (not any other Lisp);
that the code quoted is all the code, so there are no additional declarations or anything like that.
Here is an example where there is a global special declaration in effect:
;;; Declare *X* globally special, but establish no top-level binding
;;; for it
;;;
(defvar *x*)
(defun foo ()
;; FOO refers to the dynamic binding of *X*
*x*)
;;; Call FOO with no binding for *X*: this will signal an
;;; UNBOUND-VARIABLE error, which we catch and report
;;;
(handler-case
(foo)
(unbound-variable (u)
(format *error-output* "~&~S unbound in FOO~%"
(cell-error-name u))))
(defun bar (x)
;; X is lexical in BAR
(let ((*x* x))
;; *X* is special, so calling FOO will now be OK
(foo)))
;;; This call will therefore return 3
;;;
(bar 3)
Here is an example where there are nonglobal special declarations.
(defun foo (x)
;; X is lexical
(let ((%y% x))
(declare (special %y%))
;; The binding of %Y% here is special. This means that the
;; compiler can't know if it is referenced so there will be no
;; compiler message even though it is unreferenced in FOO.
(bar)))
(defun bar ()
(let ((%y% 1))
;; There is no special declaration in effect here for %Y%, so this
;; binding of %Y% is lexical. Therefore it is also unused, and
;; tere will likely be a compiler message about this.
(fog)))
(defun fog ()
;; FOG refers to the dynamic binding of %Y%. Therefore there is no
;; compiler message even though there is no apparent binding of it
;; at compile time nor gobal special declaration.
(declare (special %y%))
%y%)
;;; This returns 3
;;;
(foo 3)
Note that in this example it is always lexically apparent what binding should be in effect for %y%: just looking at the functions on their own tells you what you need to know.
Now here are come comments on your sample code fragments.
(defun j ()
(let ((x 1))
(i)))
(defun i ()
(+ x x))
> (j)
<error>
This is illegal in CL: x is not bound in i and so a call to i should signal an error (specifically an unbound-variable error).
(defun i2 (x)
(+ x x))
(defun k ()
(let ((x 1))
(i2 2)))
> (k)
4
This is fine: i2 binds x lexically, so the binding established by k is never used. You will likely get a compiler warning about unused variables in k but this is implementation-dependent of course.
(setq x 3)
(defun z () x)
> (let ((x 4)) (z))
<undefined>
This is undefined behaviour in CL: setq's portable behaviour is to mutate an existing binding but not to create a new bindings. You are trying to use it to do the latter, which is undefined behaviour. Many implementations allow setq to be used like this at top-level and they may either create what is essentially a global lexical, a global special, or do some other thing. While this is often done in practice when interacting with a given implementation's top level, that does not make it defined behaviour in the language: programs should never do this. My own implementation squirts white-hot jets of lead from hidden nozzles in the general direction of the programmer when you do this.
(defvar x 1)
(defun f (x) (g 2))
(defun g (y) (+ x y))
> (f 5)
7
This is legal. Here:
defvar declares x globally special, so all bindings of x will be dynamic, and establishes a top-level binding of x to 1;
in f the binding of its argument, x will therefore be dynamic, not lexical (without the preceding defvar it would be lexical);
in g the free reference to x will be to its dynamic binding (without the preceding defvar it would be a compile-time warning (implementation-dependent) and a run-time error (not implementation-dependent).
I came across a rather unexpected behavior today, and it utterly contradicted what (I thought) I knew about mutability in Racket.
#lang racket
(define num 8)
;(define num 9)
Uncommenting the second line gives back the error "module: duplicate definition for identifier in: num", which is fine and expected. After all, define is supposed to treat already defined values as immutable.
However, this makes no sense to me:
#lang racket
(define num 8)
num
(define define 1)
(+ define define)
It returns 8 and 2, but...
define is not set!, and should not allow the redefinition of something already defined, such as define itself.
define is a core language feature, and is clearly already defined, or I should not be able to use num at all.
What gives? Why is define, which is used to create immutable values, not immutable to itself? What is happening here?
(define define 1)
This example shows shadowing, which is different from mutation.
Shadowing allocates new locations in memory. It does not mutate existing ones.
Concretely, the new define shadows the define from Racket.
All languages with a notation of local scope allow shadowing, eg:
> (define x 10)
> (define (f x) ; x shadowed in function f
(displayln x)
(set! x 2) ; (local) x mutated
(displayln x))
> (f 1)
1
2
; local x is out of scope now
> (displayln x) ; original x unmutated
10
For the other example,
(define num 8)
;(define num 9)
this demonstrates that you cant shadow something within the same scope, which is also standard in other languages, eg:
> (define (g x x) x) ; cant have two parameters named x
When a top-level definition binds an identifier that originates from a macro expansion, the definition captures only uses of the identifier that are generated by the same expansion due to the fresh scope that is generated for the expansion.
In other words, the transformers (macros) that are required from other modules can be re-defined because they're expanded out by the macro expander (so the issue is not quite about mutability) Moreover, since racket is all about extensibility, there are no reserved keywords and additional functionality can be added to the current define through a macro (or a function) - that's why it can be redefined.
define is defined as macro of this form - see here.
#lang racket
(module foo1 racket
(provide foo1)
(define-syntaxes (foo1)
(let ([trans (lambda (syntax-object)
(syntax-case syntax-object ()
[(_) #'1]))])
(values trans))))
; ---
(require 'foo1)
(foo1)
; => 1
(define foo1 9)
(+ foo1 foo1)
; => 18
Let's say I have some module foo.rkt that provides x at phase 1.
#lang racket
(begin-for-syntax
(define x 5)
(provide x))
When you run (module->exports "foo.rkt") you get back ((1 (x ()))), meaning that x is provided at phase 1 and no other bindings are provided.
Now, in another module I could statically import x during run time using for-template:
#lang racket
(require (for-template "foo.rkt"))
x ; => 5
But this is static, and so it will always happen.
If this was at phase 0 I could use dynamic-require. But it seems like you can only use dynamic-require to run phase 1 code, not get any values from that ran code.
There is also dynamic-require-for-syntax, but I could never manage to work.
Finally, there's also namespace-require, but then it brings it into the namespace's phase 1, rather than phase 0. So I could do something like (eval '(begin-for-syntax (writeln x)), but that will only print the value of x, not return it.
There's also namespace-variable-value, but it also only seems to return values at phase 0.
So, is there anyway that I can dynamically (not statically) import a phase 1 variable from a module?
Yes there is a way, but its kind of disgusting.
First of all, we need to make a base namespace, so something like (define ns (make-base-namespace)) will do the trick.
Next, I would actually recommend using namespace-require/expansion-time rather than namespace-require. It will only instantiate the module (aka only run phase 1 code).
Doing this, x is not imported into the namespace, but at phase 1, so we can write a macro to 'smuggle' it from phase 1 to phase 0 through 3d syntax.
The macro is going to look something like:
(eval '(define-syntax (cheater-x stx)
#`'#,(datum->syntax #f x)))
And now you can just do (eval 'cheater-x) to get the value of x.
Overall your code should look something like this:
(define (dynamic-require-from-syntax module binding)
(define ns (make-base-namespace))
(parameterize ([current-namespace ns])
(namespace-require 'racket)
(namespace-require/expansion-time module)
(eval `(define-syntax (cheater-x stx)
#`'#,(datum->syntax #f ,binding)))
(eval 'cheater-x)))
(dynamic-require-from-syntax "foo.rkt" 'x) ; => 5
Obviously you could set up this function to use the same namespace on multiple calls so that it doesn't re-instantiate the module every time you call it. But that's a different answer.