将数字相乘并将结果输出到 SCHEME 中的文件中

Multiplying numbers and outputting result in a file in SCHEME

我是 SCHEME 概念的新手,刚开始学习 Scheme(和 DrRacket)。从一些在线资源开始,包括 DrRacket Docs。按照这个和其他一些在线参考,我试图解决一个基本问题,它涉及从文件中读取 2 个数字 (data.inp),将数字相乘并在不同的文件中显示输出 (result.out) .

到目前为止,我已经能够想出以下代码,

#lang racket

(define (file->char_list path)

(call-with-input-file path

(lambda (input-port)

 (let loop ((x (read-char input-port)))

   (cond 

    ((eof-object? x) '())

    (#t (begin (cons x (loop (read-char input-port))))))))))

(define (yb) 

     ;(call-with-input-file "data.inp"
     ;(lambda (in) (read-string 14 in)
 ; ))

  ;(call-with-output-file "result.out"
  ;(lambda (output-port)
            ; (display "(* x x)" output-port))) 
; Fill in the blank
 ;(fprintf (current-output-port) "Done!~n"))

  (string->number (apply string (file->char_list "data.inp"))))
 (yb)

我无法从文件 (data.inp) 中读取数字并将它们相乘。我参考了一些以前的 Whosebug 问题,但我有点卡在这一点上。任何帮助将不胜感激:)

在 Scheme 中,大多数时候您可能希望使用默认的 "current" 端口进行输入和输出。在大多数 Unix 系统上,默认的当前输入端口链接到 stdin,默认的当前输出端口链接到 stdout.

考虑到这一点,读取两个数字并写出他们的乘积基本上是:

(display (* (read) (read)))

现在,如果你想使用实际的输入和输出文件,就像你在问题中提到的那样,那么你可以用 with-input-from-file/with-output-to-file 换行(这会暂时改变当前的输入和输出端口):

(with-input-from-file "data.inp"
  (lambda ()
    (with-output-to-file "result.out"
      (lambda ()
        (display (* (read) (read)))))))

或者您可以显式指定端口,并保持 current/default 输入和输出端口不变:

(call-with-input-file "data.inp"
  (lambda (in)
    (call-with-output-file "result.out"
      (lambda (out)
        (display (* (read in) (read in)) out)))))