Why Racket treats differently mutation on REPL and mutation using both the definition window and the REPL? - racket

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.

Related

What is the proper way to construct a clojure macro from lists of symbols?

Imagine the following code to dynamically create a macro:
(def a (list '+ 1 2))
(def b (list '- 10 5))
(def c (list '/ 22 2))
(defmacro gg [h]
(let [k# `~h]
k#))
The intent is to pass a vector of symbols to a macro, do some evaluation on each element of the vector such that it returns a nice macro-esque form, then have the macro combine them into a nice macro and evaluate it. The above example works all except the actual evaluation.
When I run it I get:
(gg [a b c])
=> [(+ 1 2) (- 10 5) (/ 22 2)]
What is the secret to passing a symbol that is a list of symbols and getting a macro to evaluate them? I have tried lots of combinations of quoting and have yet to hit the right one.
The real purpose of this question is to build an Archimedes Ogre query based on a definition of a path through the graph. If someone has an example of that, I would be grateful.
EDIT:
(defmacro gg2 [h]
`(do ~#(map identity h)))
(macroexpand '(gg2 [a b c]))
=> (do a b c)
(gg2 [a b c])
=> (/ 22 2)
I was hoping to get 11 rather than the form.
You don't need a macro. Macros don't do what you're looking for here. What you are looking for is eval.
(def a '/)
(def b 22)
(def c 2)
(eval (list* [a b c]))
=> 11
Of course, you can write a macro which expands into (eval (list* ...)) if you want. It could just as well be a function though.
This is a very common mistake when starting out with macros; trying to write a macro which depends on the run-time value of its arguments. Macros run at compile-time, and generally the values of the symbols which you pass to a macro are not yet available when the macro is expanded.
About the use of eval, some cautions are in order. No one said it better than Paul Graham:
Generally it is not a good idea to call eval at runtime, for two reasons:
It’s inefficient: eval is handed a raw list, and either has to compile it on the spot, or evaluate it in an interpreter. Either way is slower than compiling the code beforehand, and just calling it.
It’s less powerful, because the expression is evaluated with no lexical context. Among other things, this means that you can’t refer to ordinary variables visible outside the expression being evaluated.
Usually, calling eval explicitly is like buying something in an airport gift-shop. Having waited till the last moment, you have to pay high prices for a limited selection of second-rate goods.

Lisp: Macros vs Functions [duplicate]

This question already has answers here:
What can you do with Lisp macros that you can't do with first-class functions?
(8 answers)
Closed 5 years ago.
In my quest to fully understand the so powerful lisp macros a question came to my mind. I know that a golden rule about macros is the one saying "Never use a macro when a function will do the work".
However reading Chapter 9 - Practical: Building a Unit Test Framework - from the book Practical Common Lisp I was introduced to the below macro whose purpose was to get rid of the duplication of the test case expression, with its attendant risk of mislabeling of results.
;; Function defintion.
(defun report-result (result form)
(format t "~:[FAIL~;pass~] ... ~a~%" result form))
;; Macro Definition
(defmacro check (form)
`(report-result ,form ',form))
OK, I understand its purpose but I could have done it using a function instead of a macro, for instance:
(setf unevaluated.form '(= 2 (+ 2 3)))
(defun my-func (unevaluated.form)
(report-result (eval unevaluated.form) unevaluated.form))
Is this only possible because the given macro is too simple ?
Furthermore, is Lisp Macro System so powerful relatively its opponents due to the code itself - like control structures, functions, etc - is represented as a LIST ?
But if it were a macro you, could have done:
(check (= 2 (+ 2 3)))
With a function, you have to do:
(check '(= 2 (+ 2 3)))
Also, with the macro the (= 2 (+ 2 3)) is actually compiled by the compiler, whereas with the function it's evaluated by the eval function, not necessarily the same thing.
Addenda:
Yes, it's just evaluating the function. Now what that means is dependent upon the implementation. Some can interpret it, others can compile and execute it. But the simple matter is that you don't know from system to system.
The null lexical environment that others are mentioning is also a big deal.
Consider:
(defun add3f (form)
(eval `(+ 3 ,form)))
(demacro add3m (form)
`(+ 3 ,form))
Then observe:
[28]> (add3m (+ 2 3))
8
[29]> (add3f '(+ 2 3))
8
[30]> (let ((x 2)) (add3m (+ x 3)))
8
[31]> (let ((x 2)) (add3f '(+ x 3)))
*** - EVAL: variable X has no value
The following restarts are available:
USE-VALUE :R1 Input a value to be used instead of X.
STORE-VALUE :R2 Input a new value for X.
ABORT :R3 Abort main loop
Break 1 [32]> :a
That's really quite damning for most use cases. Since the eval has no lexical environment, it can not "see" the x from the enclosing let.
The better substitution would be not with eval, which won't perform as expected for all cases (for example, it doesn't have access to the lexical environment), and is also overkill (see here: https://stackoverflow.com/a/2571549/977052), but something using anonymous functions, like this:
(defun check (fn)
(report-result (funcall fn) (function-body fn)))
CL-USER> (check (lambda () (= 2 (+ 2 3))))
By the way, this is how such things are accomplished in Ruby (anonymous functions are called procs there).
But, as you see, it becomes somewhat less elegant (unless you add syntax sugar) and, there's actually a bigger problem: ther's no function-body function in Lisp (although there may be non-standard ways to get at it). Overall, as you see, for this particular task the alternative solutions are substantially worse, although in some cases such approach could work.
In general, though, if you want to do something with the source code of the expressions passed into the macro (and usually this is the primary reason of using macros), functions would not be sufficient.
The report-result function needs both the source code and the result of the execution.
The macro CHECK provides both from a single source form.
If you put a bunch of check forms into the file, they are easily compiled using the usual process of compiling Lisp files. You'll get a compiled version of the checking code.
Using a function and EVAL (better use COMPILE) you would have deferred the source evaluation to a later time. It would also not be clear if it is interpreted or compiled. In case of compilation, you would then later get the compiler's checks.

Generalized Threading Macro in Clojure

Note: this is NOT about concurrency. This is about the thread macro.
I know that -> puts the object at the 2nd position and ->> puts the argument at the last position.
Now, I'm curious, much like the short hand notation of #( ... % ) for functions, is there a short hand notation for threads that lets me place the argument at arbitrary location?
The goal would be that instead of having a fixed location for the thread to run through ... I can write arbitrary forms, and insert %% at special places, and the %% is where the thread gets inserted.
Thanks!
There is now a generalized threading macro in Clojure since 1.5 called as->.
This tweet gives an example of how it works: https://twitter.com/borkdude/status/302881431649128448
(as-> "/tmp" x
(java.io.File. x)
(file-seq x)
(filter (memfn isDirectory) x)
(count x))
First 'x' is bound to "/tmp" and a file is made out of it. 'x' is rebound again to the resulting file and a put through the 'file-seq' function, etc.
The 'diamond wand' from Swiss Arrows library would do what you're asking for:
(-<> 0
(* <> 5)
(vector 1 2 <> 3 4))
; => [1 2 0 3 4]
That said, it isn't something you end up needing often (or ever in my Clojure experience)
In case anyone else comes across this, there is a reason the provided macros exist, but an arbitrary placement one does not: the latter would lead to poor API design.
The -> macro places the argument in the first position. This corresponds to functions that work on some subject argument, e.g., conj, assoc.
The ->> macro places the argument in the last position. This corresponds to functions that work on sequences, e.g., map, reduce.
Design your APIs well, and you'll be less likely to need such a macro.
There was a library that provided this feature, but I forgot where. It might of been in the deprecated clojure-contrib. It was the -$> macro.
But you could derive one from clojure's core -> macro to make the one you're looking for:
(defmacro -$>
([x] x)
([x form] (if (seq? form)
(with-meta (map #(if (= %1 '$) x %1) form) (meta form))
(list form x)))
([x form & more] `(-$> (-$> ~x ~form) ~#more)))
And use $ to indicate the insertion point:
user=> (-$> 2 str (identity $) (println $))
2
nil
Technically, you could use multiple $ in one form. But this implementation suffers from expanding the same form multiple times (in exchange for simplicity).

In LISP how to inspect free variables in a closure?

In lisp I can bind free variables bound in a closure like this...
(let ((x 1) (y 2) (z 3))
(defun free-variables () (+ x y z)))
(free-variables)
results in ...
6
What I want to know is if it is possible to inspect bound closure variables dynamically?
E.g.
(inspect-closure free-variables)
resulting in something like...
((x 1) (y 2) (z 3))
Thanks SO
Common Lisp
Access to the closure's internal variables is only possible from functions in the same scope (See Jeff's answer). Even those can't query somewhere for these variables. This functionality is not provided by the Common Lisp standard.
Obviously in many cases individual Common Lisp implementations know how to get this information. If you look for example at the SLIME code (a Common Lisp development environment) for GNU Emacs, the code for inspect and backtrace functionalities should provide that. The development wants to show this - for the user/programmer the Common Lisp standard does not provide that information.
You can have multiple functions inside an enclosure, so just add another function
(defun inspect-closure () (list (list 'x x) (list 'y y) (list 'z z)))
and put it inside your let statement
If you're trying to create a function that will access -any- closure then, strictly speaking, I don't think it's possible. x, y, and z are defined locally so if you want to announce them to the world it has to come from within the closure. What you COULD do is build a macro that duplicates let functionality with the added ability to return its local variables. You'll probably want to name it something different, like mylet or whatever.

Assigning the result of an expression to a variable

Working with DrScheme (language-- Pretty Big). Trying to pass the result of an expression to a variable that can later be used in another expression. Here is a simplified version of the problem:
Definitions window:
(define (tot a b c) (+ a b c))
(define (tot2) (+ (tot a b c) 1))
Interpreter window
> (tot 5 6 7)
18
> (tot2)
. . reference to undefined identifier: a
The result I want, of course, is 19. It would be easy to have DrScheme do all the algebra at once, but I need to have it solve the first expression, then solve the second expression based on the result of the first.
Is this what you are looking for?
(define (tot a b c) (+ a b c))
(define (tot2 a b c) (+ (tot a b c) 1))
Then
(tot2 5 6 7)
should result in 19.
If you want tot2 assigned to the integer value rather than to a function,
(define (tot a b c) (+ a b c))
(define tot2 (+ (tot 5 6 7) 1))
assigns the result of the expression (+ (tot 5 6 7) 1) to the name tot2
Scheme is lexically scoped: so a, b, and c will only exist for the dynamic extent of tot.
The dynamic extent of a procedure call is the period between when the call is initiated and when it returns (via gnu).
You're imagining a "persistence" that isn't there, though it's probably plausible, given prior experience with math.
That is: if I'm solving a math problem, and I say that x equals 5, well then x should stay equal to five for the remainder of the problem; until I erase the board, for instance.
So, can you write a programming language like this? Yes! In fact, I could write a small macro in DrScheme for you that produced exactly the behavior you appear to be looking for: it would set up a global table of variables so that every variable binding caused an update to this single table of variables.
BUT! All of the programmers I surveyed (one) (okay, it was me) agreed that this would be a very bad idea.
To see why, imagine that I have a large program that contains several variables called 'a'. Then, any time someone in part A of the program calls a function with a variable named 'a', then part B of the program will suddenly change its behavior. This will make it nearly impossible to reason about the behavior of larger programs.
More generally, this is the problem with "state" and "mutation".
For this reason, you cannot refer to variables other than the ones that are "in scope". That is, those variables whose binding form (in this case a 'define') encloses the reference.
Based on your comments on John's answer, I think what you want is just to assign the result of each function call to a variable (either one variable for each or stick them all in a list) and then add those results together.
After reading through everyone's comments, I realized that I was confusing two issues: having the interpreter evaluate an expression with variables, and actually supplying values for those variables. Because of this confusion, the questions I asked did not make sense. Here's a simplified version of the solution. As you can see, it is embarrassingly simple-- I just used "read" to have the user enter the values.
(define a (read))
(define b (read))
(define c (read))
(define d (read))
(define ee (read))
(define f (read))
(define tot (+ a b c))
(define tot2 (+ d ee f))
(define grandtotal (+ tot tot2))
(display grandtotal)
I used this approach with the actual program and now have a nice little application that totals my hours worked for the week. Thanks everyone for your patient assistance.