当前位置: 动力学知识库 > 问答 > 编程问答 >

scheme - 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?

网友答案:
(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.)

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: