How to redefine a standard function within a scope in Racket? - scheme

I would like to redefine a standard Racket function, namely display, within a lexical scope, as in this example:
(with-custom-display (display "hello"))
This should work even when the code within the scope of with-custom-display is from a different library or even racket/* packages.
Is this possible? If so, how to do it?
EDIT:
If not possible in general, at least for the case of display and other write functions... could I somehow transform every output by parameterizing on current-output-port then redirecting the transformed output to the original port?

While its not possible1 to globally replace arbitrary functions in Racket, you absolutely CAN change the standard out port that a Racket program uses (and by extension, functions like display). In fact, this is exactly what the readline collection in racket does, except for input ports rather than output ports.
Basically, all you need to do is parameterize current-output-port globally to be your special port. Since you want to ultimately write out to the original output port (but with colors), you can also grab the original output port before changing it to the new one. Your resulting code would look something like this:
#lang racket/base ;; init.rkt
(define orig-port (current-output-port))
(define new-output-port
.... uses orig-port ....)
(current-output-port new-ouput-port)
(replacing .... uses orig-port .... with the implementation of your new colored output port)
And now, any file that requires "init.rkt" will get color in its default output port.
(Note though that if you have multiple files that do this same sort of thing, you have to be careful to make sure that they don't happen in an unsafe order.)
You can also make your with-custom-display form as a simple language extension by doing:
#lang racket ;; custom-disp.rkt
(provide with-custom-display)
(require syntax/parse/define)
(define orig-port (current-output-port))
(define new-output-port
.... uses orig-port ....)
(define-simple-macro (with-custom-display body ...)
(parameterize ([current-output-port new-output-port])
body ...))
This is the general idea of how DrRacket is able to print output to a DrRacket specific repl, rather than your consoles stdout.
1Normally anyway, there are usually ways to break things if you really want to. But that's almost always a bad idea. ;)

Related

Get variable value with a string in scheme

How can we get variable value with a string in scheme language as we can achieve this in Common Lisp:
> (defvar s 3)
> S
> (symbol-value (intern "S"))
> 3
I am accessing a parameter of parent function from the closure.
EDIT: I have found this solution, but I can't use eval because it evaluates at top level. Searching for alternatives.
(eval (string->symbol "s"))
EDIT 2: I have found that Common lisp code also try to find symbol in global space. So this question is basically for both Lisps(Common Lisp, Scheme).
Don't do that!
Variables are for when you know the variable at compile time. In that case it is never a string. You can still reason about strings in compile time but your code also needs to have a relation with the name for it to be interesting. When you use eval or other forms that evaluate structure and compile/run data in runtime you are probably not doing it right (but not always. I've in my 20 year career used eval intentionally in production code twice)
If you want to store values you use a data structure. An assoc would mimic a dynamic environment. You can also use a hash with a level indicator if the size is harmless.
You can't do what you want to do and in fact it is a confused thing to want to do.
Here's why what you are trying to do is confused. Consider how a Lisp system for which it was possible to do what you wanted would work. In particular consider something like this:
(define (foo a name)
(let ([b 10])
(display (get-value name))
(* a b)))
Where get-value is meant to be how you get the binding of whatever something is.
So, if I call (foo 10 "b") it should print 10 and return 100.
But wait: b is a compile-time constant in this code. Any compiler worth its salt is going to immediately turn this into
(define (foo a name)
(display (get-value name))
(* a 10))
And now there is no binding of b.
So there are two options here: what you want to work works and it is impossible to ever write a reasonable compiler for Scheme, or what you want to work doesn't work, and it is.

How to determine if a variable exists in Chicken Scheme?

Is there a way in Chicken Scheme to determine at run-time if a variable is currently defined?
(let ((var 1))
(print (is-defined? var)) ; #t
(print (is-defined? var)) ; #f
EDIT: XY problem.
I'm writing a macro that generates code. This generated code must call the macro in mutual recursion - having the macro simply call itself won't work. When the macro is recursively called, I need it to behave differently than when it is called initially. I would use a nested function, but uh....it's a macro.
Rough example:
(defmacro m (nested)
(if nested
BACKQUOTE(print "is nested")
BACKQUOTE(m #t)
(yes, I know scheme doesn't use defmacro, but I'm coming from Common Lisp. Also I can't seem to put backquotes in here without it all going to hell.)
I don't want the INITIAL call of the macro to take an extra argument that only has meaning when called recursively. I want it to know by some other means.
Can I get the generated code to call a macro that is nested within the first macro and doesn't exist at the call site, maybe? For example, generating code that calls (,other-macro) instead of (macro)?
But that shouldn't work, because a macro isn't a first-class object like a function is...
When you write recursive macros I get the impression that you have an macro expansion (m a b ...) that turns into a (m-helper a (b ...)) that might turn into (let (a ...) (m b ...)). That is not directly recursive since you are turning code into code that just happens to contain a macro.
With destructuring-bind you really only need to keep track of two variables. One for car and one for cdr and with an implicit renaming macro the stuff not coming from the form is renamed and thus hygenic:
(define-syntax destructuring-bind
(ir-macro-transformer
(lambda (form inject compare?)
(define (parse-structure structure expression optional? body)
;;actual magic happens here. Returns list structure with a mix of parts from structure as well as introduced variables and globals
)
(match form
[(structure expression) . body ]
`(let ((tmp ,expression))
,(parse-structure structure 'tmp #f body))))))
To check if something from input is the same symbol you use the supplied compare? procedure. eg. (compare? expression '&optional).
There's no way to do that in general, because Scheme is lexically scoped. It doesn't make much sense to ask if a variable is defined if an referencing an undefined variable is an error.
For toplevel/global variables, you can use the symbol-utils egg but it is probably not going to work as you expect, considering that global variables inside modules are also rewritten to be something else.
Perhaps if you can say what you're really trying to do, I can help you with an alternate solution.

Changing the current input port in racket

How can I change the input port in racket?
That is, suppose I create a new input port:
(define my-port (open-input-string "this is a test"))
How can I make it so that (current-input-port) returns my-port now?
To add to Chris' answer; the current input port is what's known as a "parameter", which is very approximately a dynamically scoped setting/variable. In general, it's cleaner and more conservative to set the current input port only temporarily, using 'parameterize'. Like this:
(parameterize ([current-input-port my-port])
... do some stuff ...
)
Evaluating this code will cause the input-port to be set for your body code and any code that it calls, but won't "bleed over" into code that's evaluated outside; it will also undo the change on an exceptional or continuation-based exit.
(current-input-port my-port)
Don't do this at the racket REPL! This will cause all subsequent REPL input to come from that source. (It's okay to run inside DrRacket, however, even in the DrRacket REPL.)

looking up the text of a procedure in scheme

The ipython python shell has a wonderful feature, whereby you can type:
foo??
and see the text of function foo.
Does scheme (in particular, MIT scheme), have anything like this?
I want to be able to say
(define (foo x) (* x x))
and later view (or even operate on) the list (* x x).
Is there a way to do this?
Not by default in any Scheme I know. What you can do is define a macro that does what "define" does and in addition stores the body of the function in a hash table or an alist or whatever. That will only work on code that you control, of course.
There's no reliable, portable way to do this.
The general structure of a Scheme function is (define (<name> <arg1> <arg2> ... ) <expr1> <expr2> ... <exprn>). Extending Mark Probst's suggestion, you could define a macro that defines a quoted version of the function, which you could then apply cddr to to get a list of the function's expressions.

How can you re-define a constant identifier in DrScheme?

I am using DrScheme to write a Scheme interpreter. I define a Read Eval Print Loop and I am re-defining the eval procedure. This works fine in other scheme implementations like Chez Scheme, but I don't like the code editing in Chez Scheme, so I would like to use DrScheme for this.
When I make a definition such as:
(define (eval exp env) (cond ...))
It says:
define-values: cannot change constant identifier: eval
Is there a way to override that and let me change constant identifiers? I'd prefer not to have to rename all my variables to get around this.
It turns out there are options per each language and one of them is "Disallow redefinition of initial bindings" which can be unchecked.
You're probably using the "Pretty Big" language. Switch to "Module", and you can do it.

Resources