I am happily using DrRacket with the inbuilt SICP language (https://docs.racket-lang.org/sicp-manual/SICP_Language.html) to work through SICP.
However, I'm unable to use the DrRacket debugger with the SICP language.
A simple test example,
#lang racket
(define (test x)
(* x x))
(test (test (test 2)))
debugs happily, and I can step through and see 'x' being updated etc.
However, using the SICP language as follows
#lang sicp
(define (test x)
(* x x))
(test (test (test 2)))
results in an error:
Library/Racket/7.5/pkgs/sicp/sicp/main.rkt:67:32: ?: cannot bind from tainted syntax in: (quote #%kernel)
Does anyone know what the problem might be? I've not really had to use the debugging yet, but I would quite like knowing that it's there if I do want to use it.
Related
I have quite simple set of .rkt sources and, say, "a.rkt" and "b.rkt" among them. I'd like to be able to write (require "a.rkt") in "b.rkt" and vice versa. Now I'm facing error about "loading cycle".
Can I solve this issue with bare modules without adding units? Does Racket have anything similar to forward declaration so I could simple add missing signature instead of requiring? If both answers are "No", does someone know good and understandable tutorial on how to implement units with typed/racket (aside of official docs)?
You can use lazy-require:
;; a.rkt
#lang racket
(require racket/lazy-require)
(lazy-require ["b.rkt" (b)])
(provide a)
(define (a) 'a)
(list (a) (b))
;; b.rkt
#lang racket
(require racket/lazy-require)
(lazy-require ["a.rkt" (a)])
(provide b)
(define (b) 'b)
(list (a) (b))
Notice that you must tell lazy-require the specific things you want to import. That's because it is implemented in terms of dynamic-require plus set!.
If you peek at the source for xrepl, you'll see it define a defautoload macro, which (modulo some N/A details) is simply:
(define-syntax-rule (defautoload libspec id ...)
(begin
(define id
(make-keyword-procedure
(λ (kws kw-args . args)
(set! id (dynamic-require 'libspec 'id))
(keyword-apply id kws kw-args args))))
...))
I'm currently learning Scheme (using Racket), but one of the challenges I'm coming upon is trying to execute the following bit of code, which is meant to execute Racket code from user input using eval:
(display (eval (read)))
Here's some of the weird behavior I've observed so far:
(display (eval (read))) in the definition window prompts for keyboard input, as expected, when the definitions are run. However, providing the input
((lambda (x) (+ x 1)) 1)
gives the error
?: function application is not allowed;
no #%app syntax transformer is bound in: ((lambda (x) (+ x 1)) 1)
On the other hand, using (display ((eval (read)) 1)) and providing input
(lambda (x) (+ x 1))
returns the error
lambda: unbound identifier;
also, no #%app syntax transformer is bound in: lambda
However, running (display (eval (read))) and providing ((lambda (x) (+ x 1)) 1) in the console pane, as opposed to the definitions pane, prints out 2, as expected.
What is the reason for this behavior?
It looks like you don't have the namespace set up. If you're running (eval (read)) within a file, it doesn't work because the current-namespace is set to an empty namespace by default. You can set up a namespace with racket/base in it by doing (current-namespace (make-base-namespace)) first:
#lang racket
(current-namespace (make-base-namespace))
(println (eval (read)))
Running this program and giving it the input ((lambda (x) (+ x 1)) 1) results in it printing 2.
The reason it worked in the interactions window (item 3 of your weird-behavior list), is that in the interactions window, the current-namespace parameter is set to the namespace of the file.
This is not true for the definitions window, the main program, so you have to set the current-namespace yourself, or pass a namespace in as a second argument to eval:
#lang racket
(define ns (make-base-namespace))
(println (eval (read) ns))
Racket, the software package, has support for both R5RS and R6RS and will probably get support for R7RS. The software also has several non standard languages in its own Racket language family that has much in common with Scheme but is not Scheme. Alex has made an excellent answer for that language so I though I'd add information about Scheme since you write you're learning Scheme which is not the same as learning Racket when it comes some corner cases including eval.
eval is a procedure which has had breaking changes between the different Scheme reports since it became mandatory in R5RS. Here are some examples from different versions of the standard:
#!r6rs
(import (rnrs)
(rnrs eval))
(display (eval '((lambda (x) (+ x 1)) 1)
(environment '(rnrs))))
; ==> undefined, prints 2
The slightly older but still in common used R5RS:
#!r5rs
(display (eval '((lambda (x) (+ x 1)) 1)
(scheme-report-environment 5)))
; ==> undefined, prints 2
The to come R7RS which only has it's small version ratified so far:
#!r7rs
(import (scheme)
(scheme eval))
(display (eval '((lambda (x) (+ x 1)) 1)
(environment '(scheme))))
; ==> undefined, prints 2
I am trying to use the check-expect function in scheme but I keep being told its an unbound identifier for check-expect. Isn't check-expect a function I can use already? Below is my code:
#lang racket
(define contains (lambda (item list*)
(if (equal? list* '())
#f
(if (equal? item (car list*))
#t
(contains item (cdr list*))))))
(define z (list 1 2 3))
(define q (list 4 5 6))
(define p (list "apple" "orange" "carrot"))
(check-expect (contains 1 z) #t)
Old question, but answer for the googlers:
You can (require test-engine/racket-tests), which defines check-expect.
Note that, unlike BSL, you'll have to run the tests with (test).
check-expect is not technically built into scheme or Racket automatically.
Note that you are using #lang racket. That is the professional Racket language, and that language expects you to know and state explicitly what libraries to import. It will not auto-import them for you.
(Now, you could require a unit testing library; there is one that comes with the Racket standard library.)
But if you are just starting to learn programming, it makes much more sense to use one of the teaching languages within Racket.
For the code you're using above, I suspect you'll probably want this instead. Start DrRacket and choose "Beginner Student Language" from the "How to Design Programs" submenu in the "Language" menu.
See http://www.ccs.neu.edu/home/matthias/HtDP2e/prologue.html for more details.
I've managed to come up with this workaround:
At the top of the file (but after #lang racket) added a line
(require rackunit)
Instead of (check-expect) I've used
(check-equal? (member? "a" (list "b" "a")) #f )
Unlike in check-expect, tests must be added after the function definitions.
If the checks are successful, there is no output. Only when a tests fails, the output looks like this:
--------------------
FAILURE
name: check-equal?
actual: #f
expected: #t
expression: (check-equal? #f (member? "a" (list "b" "a")))
message: "test"
More Info: RackUnit documentation
I took a class using DrRacket and looked at the first assignment in Terminal (Mac).
The line in this file, automatically added by DrRacket, which made check-expect available is:
#reader(lib "htdp-beginner-reader.ss" "lang")((modname basic) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
As a side note, I wanted to try a Racket program without DrRacket. Just to test, I decided to do (+ 1 2). To get it to work, my file looks like this:
#! /Applications/Racket\ v6.2.1/bin/racket
#lang racket
(+ 1 2)
I run it in Terminal like this:
racket test.rkt
I put this in .bash_profile:
alias racket='/Applications/Racket\ v6.2.1/bin/racket'
I am trying to write a small scheme-like language in python, in order to try to better understand scheme.
The problem is that I am stuck on syntax objects. I cannot implement them because I do not really understand what they are for and how they work.
To try to understand them, I played around a bit with syntax objects in DrRacket.
From what I've been able to find, evaluating #'(+ 2 3) is no different from evaluating '(+ 2 3), except in the case that there is a lexical + variable shadowing the one in the top-level namespace, in which case (eval '(+ 2 3)) still returns 5, but (eval #'(+ 2 3)) just throws an error.
For example:
(define (top-sym)
'(+ 2 3))
(define (top-stx)
#'(+ 2 3))
(define (shadow-sym)
(define + *)
'(+ 2 3))
(define (shadow-stx)
(define + *)
#'(+ 2 3))
(eval (top-sym)), (eval (top-stx)), and (eval (shadow-sym)) all return 5, while (eval (shadow-stx)) throws an error. None of them return 6.
If I didn't know better, I would think that the only thing that's special about syntax objects (aside from the trivial fact that they store the location of the code for better error reporting) is that they throw an error under certain circumstances where their symbol counterparts would have returned a potentially unwanted value.
If the story were that simple, there would be no real advantage to using syntax objects over regular lists and symbols.
So my question is: What am I missing about syntax objects that makes them so special?
Syntax objects are the repository for lexical context for the underlying Racket compiler. Concretely, when we enter program like:
#lang racket/base
(* 3 4)
The compiler receives a syntax object representing the entire content of that program. Here's an example to let us see what that syntax object looks like:
#lang racket/base
(define example-program
(open-input-string
"
#lang racket/base
(* 3 4)
"))
(read-accept-reader #t)
(define thingy (read-syntax 'the-test-program example-program))
(print thingy) (newline)
(syntax? thingy)
Note that the * in the program has a compile-time representation as a syntax object within thingy. And at the moment, the * in thingy has no idea where it comes from: it has no binding information yet. It's during the process of expansion, during compilation, that the compiler associates * as a reference to the * of #lang racket/base.
We can see this more easily if we interact with things at compile time. (Note: I am deliberately avoiding talking about eval because I want to avoid mixing up discussion of what happens during compile-time vs. run-time.)
Here is an example to let us inspect more of what these syntax objects do:
#lang racket/base
(require (for-syntax racket/base))
;; This macro is only meant to let us see what the compiler is dealing with
;; at compile time.
(define-syntax (at-compile-time stx)
(syntax-case stx ()
[(_ expr)
(let ()
(define the-expr #'expr)
(printf "I see the expression is: ~s\n" the-expr)
;; Ultimately, as a macro, we must return back a rewrite of
;; the input. Let's just return the expr:
the-expr)]))
(at-compile-time (* 3 4))
We'll use a macro here, at-compile-time, to let us inspect the state of things during compilation. If you run this program in DrRacket, you will see that DrRacket first compiles the program, and then runs it. As it compiles the program, when it sees uses of at-compile-time, the compiler will invoke our macro.
So at compile-time, we'll see something like:
I see the expression is: #<syntax:20:17 (* 3 4)>
Let's revise the program a little bit, and see if we can inspect the identifier-binding of identifiers:
#lang racket/base
(require (for-syntax racket/base))
(define-syntax (at-compile-time stx)
(syntax-case stx ()
[(_ expr)
(let ()
(define the-expr #'expr)
(printf "I see the expression is: ~s\n" the-expr)
(when (identifier? the-expr)
(printf "The identifier binding is: ~s\n" (identifier-binding the-expr)))
the-expr)]))
((at-compile-time *) 3 4)
(let ([* +])
((at-compile-time *) 3 4))
If we run this program in DrRacket, we'll see the following output:
I see the expression is: #<syntax:21:18 *>
The identifier binding is: (#<module-path-index> * #<module-path-index> * 0 0 0)
I see the expression is: #<syntax:24:20 *>
The identifier binding is: lexical
12
7
(By the way: why do we see the output from at-compile-time up front? Because compilation is done entirely before runtime! If we pre-compile the program and save the bytecode by using raco make, we would not see the compiler being invoked when we run the program.)
By the time the compiler reaches the uses of at-compile-time, it knows to associate the appropriate lexical binding information to identifiers. When we inspect the identifier-binding in the first case, the compiler knows that it's associated to a particular module (in this case, #lang racket/base, which is what that module-path-index business is about). But in the second case, it knows that it's a lexical binding: the compiler already walked through the (let ([* +]) ...), and so it knows that uses of * refer back to the binding set up by the let.
The Racket compiler uses syntax objects to communicate that kind of binding information to clients, such as our macros.
Trying to use eval to inspect this sort of stuff is fraught with issues: the binding information in the syntax objects might not be relevant, because by the time we evaluate the syntax objects, their bindings might refer to things that don't exist! That's fundamentally the reason you were seeing errors in your experiments.
Still, here is one example that shows the difference between s-expressions and syntax objects:
#lang racket/base
(module mod1 racket/base
(provide x)
(define x #'(* 3 4)))
(module mod2 racket/base
(define * +) ;; Override!
(provide x)
(define x #'(* 3 4)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require (prefix-in m1: (submod "." mod1))
(prefix-in m2: (submod "." mod2)))
(displayln m1:x)
(displayln (syntax->datum m1:x))
(eval m1:x)
(displayln m2:x)
(displayln (syntax->datum m2:x))
(eval m2:x)
This example is carefully constructed so that the contents of the syntax objects refer only to module-bound things, which will exist at the time we use eval. If we were to change the example slightly,
(module broken-mod2 racket/base
(provide x)
(define x
(let ([* +])
#'(* 3 4))))
then things break horribly when we try to eval the x that comes out of broken-mod2, since the syntax object is referring to a lexical binding that doesn't exist by the time we eval. eval is a difficult beast.
I've been reading through SICP (Structure and Interpration of Computer Programs) and was really excited to discover this wonderful special form: "make-environment", which they demonstrate to use in combination with eval as a way of writing modular code (excerpt from section 4.3 on "packages"):
(define scientific-library
(make-environment
...
(define (square-root x)
...)))
They then demonstrate how it works with
((eval 'square-root scientific-library) 4)
In their example, they then go on to demonstrate exactly the usage that I would want - an elegant, minimalist way of doing the "OO" style in scheme... They "cons" together a "type", which is actually what was returned by the "make-environment" special form (i.e. the vtable), and an arg ("the state")...
I was so excited because this is exactly what I've been looking for as a way to do polymorphic dispatch "by symbol" in Scheme without having to write lots of explicit code or macros.
i.e. I want to create an "object" that has, say, two functions, that I call in different contexts... but I don't want to refer to them by "car" and "cdr", I want to both declare and evaluate them by their symbolic names.
Anyway, when I read this I couldn't wait to get home and try it.
Imagine my disappointment then when I experienced the following in both PLT Scheme and Chez Scheme:
> (make-environment (define x 3))
Error: invalid context for definition (define x 3).
> (make-environment)
Error: variable make-environment is not bound.
What happened to "make-environment" as referenced in SICP? It all seemed so elegant, and exactly what I want, yet it doesn't seem to be supported in any modern Scheme interpreters?
What's the rationale? Is it simply that "make-environment" has a different name?
More information found later
I took at look at the online version:
https://mitp-content-server.mit.edu/books/content/sectbyfn/books_pres_0/6515/sicp.zip/full-text/book/book-Z-H-28.html#%_sec_4.3
I was reading was the first edition of SICP. The second edition appears to have replaced the discussion on packages with a section on non-deterministic programming and the "amp" operator.
After more digging around I discovered this informative thread on newsnet:
"The R5RS EVAL and environment specifiers are a compromise between
those who profoundly dislike first-class environments and want a
restricted EVAL, and those who can not accept/understand EVAL without
a second argument that is an environment."
Also, found this "work-around":
(define-syntax make-environment
(syntax-rules ()
((_ definition ...)
(let ((environment (scheme-report-environment 5)))
(eval '(begin definition
...)
environment)
environment))))
(define arctic
(make-environment
(define animal 'polarbaer)))
(taken from this)
However, I ended up adopting a "message passing" style kinda of like the first guy suggested - I return an alist of functions, and have a generic "send" method for invoking a particular function by name... i.e something like this
(define multiply
(list
(cons 'differentiate (...))
(cons 'evaluate (lambda (args) (apply * args)))))
(define lookup
(lambda (name dict)
(cdr (assoc name dict))))
; Lookup the method on the object and invoke it
(define send
(lambda (method arg args)
((lookup method arg) args)))
((send 'evaluate multiply) args)
I've been reading further and am aware that there's all of CLOS if I really wanted to adopt a fully OO style - but I think even above is somewhat overkill.
They wrote it like that because MIT Scheme does, in fact, have first-class environments, and presumably that's what the writers were planning to teach their class with (since the book was written at MIT).
Check out http://groups.csail.mit.edu/mac/projects/scheme/
However, I've noticed that MIT Scheme, while still somewhat actively developed, lacks many of the features that a really modern Scheme would have, like a foreign function interface or GUI support. You probably wouldn't want to use it for a serious software development project, at least not by itself.
Scheme has no first-class environments because of performance reasons. When Scheme was created, it wasn't the fastest language around due to nifty stuff like first-class functions, continuations, etc. Adding first-class environments would have crippled the performance even further. So it was a trade-off made in the early Scheme days.
Would a classical dispatcher function work? I think this is similar to what you're looking for.
(define (scientific-library f)
(define (scientific-square-root x) (some-scientific-square-root x))
(cond ((eq? f 'square-root) scientific-square-root)
(else (error "no such function" f))))
(define (fast-library f)
(define (fast-square-root x) (some-fast-square-root x))
(cond ((eq? f 'square-root) fast-square-root)
(else (error "no such function" f))))
((scientific-library 'square-root) 23)
((fast-library 'square-root) 23)
You could even combine the example scientific and fast libraries into one big dispatch method:
(define (library l f)
(define (scientific-library f)
...)
(define (fast-library f)
...)
(cond ((eq? l 'scientific) (scientific-library f))
((eq? l 'fast) (fast-library f))
(else (error "no such library" l))))
(library 'fast 'square-root)