我目前正在使用Racket博士进行编程,而我需要做的任务是提示用户输入文件。该程序将使用输入文件中的整数值执行两个函数(two-lhs和two-rhs),这些函数计算N个平方的和,并将结果输出到提示的输出文件中。在左侧列出了具有两个lh的值,在右侧列出了具有两个rhs的值。
例如:假设目录中有一个名为“ data”的文件,其中第一行的整数为25,第二行的整数为7,第三行的整数为9。用户输入“ data”作为输入文件并输入“ testing” '作为输出文件,将在目录中使用以下值和格式创建名为'testing'的输出文件:
partial.r(subset,c("GPA","SAT"),"GRADE1", use = "complete.obs")
no warnings
这是我当前的代码,带有我的理解注释:
(results from two-lhs) (results from two-rhs)
5525 5525
140 140
285 285
我运行代码的输出文件是:
#lang racket
(define squared ;helper function for two lhs
(lambda (x) (* x x)))
(define Two-LHS
(lambda (n)
(cond((= n 0) 0)
(else
(+ (squared n) (Two-LHS(- n 1)))))))
(define Two-RHS
(lambda (n)
(cond ((= n 0) 0)
(else
(/ (* n (+ n 1) (+ (* n 2) 1)) 6)))))
(define in ;function that reads in the input file from user
(lambda ()
(let((pin(open-input-file (symbol->string (read))))) ;prompts the user for input file. pin = the input-port
(let f ((x(read pin))) ;f is a procedure that reads the input port?
(if(eof-object? x) ; x reads the value inside pin and if x happens to be end of file object
(begin ; then closes the input-port
(close-input-port pin)
'())
(cons (Two-LHS x)(cons (Two-RHS x)(f(read pin))))) ;else using the x, executes two lhs and rhs until x reaches
)))) ; end of file to close the port
(define write-lst
(lambda (lst outp) ;lst = input file, outp = output file
(if(eq? lst '()) ; if input file contains an empty list
(close-output-port outp) ; the output-port will be closed
(begin ; else execute begin
(write (car lst) outp) ; which writes the first element of the list to the output file
(display #\space outp) ; will add whitespace after each element to the output file.
(newline outp) ; was thinking this would add newline on the output file after each iteration, but need a way to add newline after every 2 whitespace.
(write-lst (cdr lst) outp))))) ;recurses back to write-lst function with the next element in the list without
;the first element until it becomes an empty list so that output-port could close.
(define out ;will be renamed to two-sum, since this is the function that will write to the output file.
(lambda (lst) ;lst = input file
(let((pout(open-output-file (symbol->string (read))))) ; prompts the user for the output file, pout = the output-port
(write-lst lst pout); uses write-list function to write out to output file
)))
(out (in))
如何使输出文件正确格式化? 任何在正确方向上的帮助将不胜感激! 谢谢。
答案 0 :(得分:1)
我们可以使用Racket的fprintf
过程来简化操作,并一次遍历列表中的两个元素-假设它具有偶数个元素:
(define write-lst
(lambda (lst outp)
(if (null? lst)
(close-output-port outp)
(begin
(fprintf outp "~a ~a~n" (car lst) (cadr lst))
(write-lst (cddr lst) outp)))))
技巧就在这里,格式为字符串:"~a ~a~n"
。它指出:打印一个对象,一个空格,另一个对象和换行。并且我们传递了当前元素(car lst)
和第二个元素(cadr lst)
-实际上,我们可以只使用易于理解的first
和second
过程。最后,在递归中,我们推进了两个元素:(cddr lst)
。