Im using emacs and mzscheme as interpreter
Welcome to Racket v8.2 [cs]
> (define (square a) (* a a))
> square 4
#<procedure:square>
> 4
I just finished setting up emacs with mzscheme, combinations are working well but my procedures doesn't seem to work. Tried everything i could find.
Related
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'm using Racket to teach (functional) programming, and I really like the way features are disabled for beginnings students. One problem however I'm having with Racket is the fact that functions seem to be hoisted even in the most restricted version. Now is there a way to disable function hoisting in racket so that the following code would produce an error?
(define (f x)
(g x)
)
(check-expect (f 3) 3)
(define (g x)
x
)
This behavior is not caused by hoisting functions. It is caused by check-expect. You can think of check-expect as being "hoisted downwards."
If you replace check-expect with your own function, you get the normal error:
g is used here before its definition
For the program:
(define (my-check-expect actual expected) ....)
(define (f x)
(g x))
(my-check-expect (f 3) 3)
(define (g x)
x)
If you want the students to only write tests after they code, you can make a teachpack that provides a new version of check-expect.
However, this is a bad idea. The Design Recipe teaches students to write functional examples/tests before they code. This special behavior of check-expect is what allows them to do that.
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.
EDIT I'm not just asking about 'indenting' every single line of code but about "pretty printing" and/or a wider definition of "indenting", where lines would be grouped/split depending on what they contain.
Here's a function (which I wrote to solve an Euler problem but that is not the point: I could have written it differently) which I'm trying to pretty print:
Version manually indented:
(apply max
(flatten
(for [x (range 100 1000)]
(map
#(if (= (str (* x %)) (apply str (reverse (str (* x %)))))
(* x %)
0)
(range x 1000)))))
Apparently this isn't the one true Lisp indentation/printing style and, as I'd like to get good habits from the start, I tried to "pretty print" it, doing the following from Emacs' slime-repl clojure REPL:
user> (doc pprint) ;; just to show which version of pprint I'm using
clojure.pprint/pprint
...
So I tried to do:
user> (pprint '(apply max
(flatten
(for [x (range 100 1000)]
(map
#(if (= (str (* x %)) (apply str (reverse (str (* x %)))))
(* x %)
0)
(range x 1000))))))
And I got the following:
(apply
max
(flatten
(for
[x (range 100 1000)]
(map
(fn*
[p1__13958#]
(if
(=
(str (* x p1__13958#))
(apply str (reverse (str (* x p1__13958#)))))
(* x p1__13958#)
0))
(range x 1000)))))
As I understand it the #(...) notation for the lambda is a "reader macro". So how can I pretty print without triggering the expansion of macros? More generally: how can I pretty print "what I see in my text editor"?
Also, is it normal that nearly everything goes on a new line? For example:
(apply
max
(flatten
(for
[x (range 100 1000)]
(map
...
seems to be a waste of quite some vertical screen real estate. Is this the way Lisp code should be indented?
And a last related question: can Emacs be configured to "pretty print" a selected region or an entire .clj buffer?
There's no "official" way to indent lisp code, but I like the way clojure-mode indents clojure code (see below).
I don't know why pprint prints code the way it does but according to this page, it's an early release that isn't feature-complete yet.
For the emacs indentation part, you might want to take a look at clojure-mode.
The closest I have seen to a consensus is to "indent it like Emacs does", I suppose to be pollitically correct I should include the corollary "indent it like vim does". the other editors like eclipse+CCW seem to match this fairly closely. though the default pretty printer adds more newlines.
Here's what I'm currently doing:
(defn pprint-code [code]
(with-pprint-dispatch code-dispatch
(binding [*print-suppress-namespaces* true]
(pprint code))))
NOTE: Look in clojure.pprint to resolve the free-vars.
It's certainly an improvement. I still don't exactly know how to tweak *print-miser-width* and/or *print-right-margin* to get better output. YMMV. My current beef is with (auto-)gensyms - I want them demangled whilst pprinting in certain contexts.
Ideally, forms/functions could define their own formatting rules, e.g. let-bindings should always be on separate lines. I'm not aware of being able to do this with clojure.core.
For reference, see this overview.
I've been slowly working my way though the exercises in Structure and Interpretation of Computer Programs. Section 1.1.5 talks about applicative vs. normal-order evaluation, and the topic has come up several times in the text afterward. Since the interpreter uses applicative-order evaluation, it's easy to just insert display debug statements in your code to see exactly how it works. It would help my understanding to be able to do the same thing for normal-order evaluation.
Does anyone know of a Scheme (or Lisp) interpreter that's implemented using normal-order evaluation instead of applicative-order?
Update:
Here's a short example modified from the one given in SICP. I'll define my own add procedure to print out the arguments, and use the square procedure from the book.
(define (add x y)
(display x)
(display y)
(newline)
(+ x y))
(define (square x) (* x x))
Now if I run the short program (square (add 1 2)) using applicative-order evaluation, the result of (add 1 2) will only be computed once then passed to the square procedure. The operands 12 should be printed once before the final result. We can just run this in an interpreter to verify that this is what happens.
> (square (add 1 2))
12
9
Using normal-order evaluation, though, the single operand (add 1 2) should be copied into the square procedure, which would evaluate as (* (add 1 2) (add 1 2)). The operands 12 should be printed twice before the final result.
I'd like to be able to run this in an interpreter that does normal-order evaluation to verify that this is indeed how it works.
Turns out Scheme actually comes with what is essentially a normal-order evaluator already. They're those fabled macros you've probably heard so much about, and we can rewrite the examples of sections 1.1.4--1.1.5 to use macro expansion in lieu of procedure application rather easily:
(define (print . items)
(for-each display items))
(define-macro (add x y)
`(begin (print "[ADD " ',x " " ',y "]")
(+ ,x ,y)))
(define-macro (mul x y)
`(begin (print "[MUL " ',x " " ',y "]")
(* ,x ,y)))
(define-macro (square x)
`(begin (print "[SQUARE " ',x "]")
(mul ,x ,x)))
(define-macro (sum-of-squares x y)
`(begin (print "[SUM-OF-SQUARES " ',x " " ',y "]")
(add (square ,x) (square ,y))))
(define-macro (f a)
`(begin (print "[F " ',a "]")
(sum-of-squares (add ,a 1) (mul ,a 2))))
Ignore the PRINTs, their logic is a little beyond where you're at in the text, but they're just a shorthand for lots of DISPLAYs. Actually, you would want to entirely forgo the tracing-by-printing in favor of using the system's macro-expansion function. but this varies with the implementation (e.g. in Ypsilon you would use (macro-expand '(f 5))).
If you load these definitions (with the caveat that DEFINE-MACRO is non-standard, but that shouldn't be a problem in practice since most Schemes provide it), then evaluating (f 5) like the book does will print out (of course I prettied it up a little):
[F 5]
[SUM-OF-SQUARES (add 5 1) (mul 5 2)]
[ADD (square (add 5 1)) (square (mul 5 2))]
[SQUARE (add 5 1)]
[MUL (add 5 1) (add 5 1)]
[ADD 5 1]
[ADD 5 1]
[SQUARE (mul 5 2)]
[MUL (mul 5 2) (mul 5 2)]
[MUL 5 2]
[MUL 5 2]
136
Which is more or less what the book illustrates the process should be.
Writing these sorts of macros is basically like writing a normal procedure, except that
Instead of DEFINE, you use DEFINE-MACRO.
There is no implicit BEGIN over the body, so you need to supply your own if you have multiple expressions.
The entire body expression is prefixed with a grave accent.
All instances of the parameters are prefixed with a comma.
That's Writing Scheme Macros 101.
Now all in all, this is a little silly to spring macros on someone on just the first chapter of SICP. But if you say you're having an inordinate amount of difficulty modifying Racket to do what you want (and then there are those not using Racket at all), then here's an alternative.
Racket has a lazy language. It's better than just an interpreter, since you can write programs that are made of plain racket modules and lazy ones.
As for debugging using printouts -- you can do that in this lazy language, and you get something similar to unsafe IO in Haskell. This can still be confusing sometimes though. (And if you wanted an interpreter to plug printouts into it, it would also be confusing, because it follows the lazy evaluation...)