2015-08-16 28 views
3

我對SCHEME的概念很陌生,剛開始學習Scheme(和DrRacket)。開始使用一些在線資源,包括DrRacket Docs。在線和其他一些參考文獻之後,我試圖解決一個基本問題,它涉及從文件(data.inp)中讀取2個數字,將數字相乘並在不同文件(result.out)中顯示輸出。SCHEME中的文件乘以數字並輸出結果

到目前爲止,我已經能夠想出下面的代碼,

#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)和乘以他們。我有參考一些以前的stackoverflow問題,但我有點卡在這一點。任何幫助將不勝感激:)

回答

4

在計劃中,大多數時候你可能會想要使用默認的「當前」端口輸入和輸出。在大多數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))))))) 

,或者你可以明確指定的端口,並離開當前/默認的輸入和輸出端口不變:

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

這工作,比我打算做的更好。爲了讓它更進一步,我現在試圖打印2個相乘的數字,並將其與輸出顯示在同一個文件中。使用'(顯示(讀入)(讀入))(*(讀入)(讀入))出)'和'(顯示(((讀入)(讀入))*(讀入)(讀入))out)'但我得到錯誤指出了參數的數量。 – Yashika