Input Output in Scheme

Other topics

Create an input port

An input port can be created in many ways, but usually the method starts with open-input-.

String port

You can use a string as a port using open-input-string. It will create a port that will be able to read from the string.

(define p
  (open-input-string "(a . (b . (c . ()))) 34"))

File port

You can open a file for reading with open-input-file.

(define p
  (open-input-file "path/to/file"))

Read from an input port

Reading from an input port can be done in many ways. We can use the read method used by the REPL. It will read and interpret space separated expressions.

Taking the example from the string port above. We can read from the port like this:

(define p
  (open-input-string "(a . (b . (c . ()))) 34"))
(read p) -> (a b c)
(read p) -> 34

We can read from a port as char using the special method read-char. This will return a single char from the port that we're reading from.

(define p (open-input-string "hello"))
(read-char p) -> #\h

Contributors

Topic Id: 8188

Example Ids: 26316,26317

This site is not affiliated with any of the contributors.