How to write to a file in tinyscheme?

2019-07-15 05:39发布

Scheme implementation : tinyscheme

Here is my try:

(with-output-to-file "biophilia.c"
  (lambda (output-port)
    (write "Hello" output-port)))

Ceates biophilia.c with following content:

Error: ( : 26) not enough arguments

What am I doing wrong here? how to repair it?

(define (with-output-to-file s p)
     (let ((outport (open-output-file s)))
          (if (eq? outport #f)
               #f
               (let ((prev-outport (current-output-port)))
                    (set-output-port outport)
                    (let ((res (p)))
                         (close-output-port outport)
                         (set-output-port prev-outport)
                         res)))))

标签: lisp scheme
1条回答
我只想做你的唯一
2楼-- · 2019-07-15 06:33

You are calling with-output-to-file incorrectly.

The second argument is a thunk, and not a procedure expecting a port argument.

So call it like:

(with-output-to-file "biophilia.c"
  (lambda ()
    (write "Hello")))

with-output-to-file already does the re-binding of the current-port for you (as you tried in your reconstruction).

See the Racket docs for it here.

查看更多
登录 后发表回答