这样做的目的是检查考虑的字符是数字还是操作数,然后将其输出到一个列表中,该列表将写出到 txt 文件中。
我想知道哪个过程会更有效率,是按照我上面说的做(将它写入列表,然后将该列表写入文件)还是直接从该过程写入 txt 文件。
我是计划的新手,所以如果我没有使用正确的术语,我深表歉意
(define input '("3" "+" "4"))
(define check
(if (number? (car input))
(write this out to a list or directly to a file)
(check the rest of file)))
我想到的另一个问题是,如何才能使检查过程递归?
我知道有很多问题,但我对查看我在其他网站上找到的方法感到有些沮丧。
我真的很感谢你的帮助!
最佳答案
将功能拆分为两个单独的过程是一个好主意,一个用于生成字符串列表,另一个用于将它们写入文件。对于第一个过程,我会给你一个大致的想法,这样你就可以填空(毕竟这是一个家庭作业),它遵循递归解决方案的标准结构:
(define (check input)
(cond ((null? input) ; the input list is empty
<???>) ; return the empty list
((string->number (car input)) ; can we convert the string to a number?
(cons "number" <???>)) ; add "number" to list, advance the recursion
(else ; the string was not a number
(cons "operand" <???>)))) ; add "operand" to list, advance recursion
对于第二部分,总体思路是这样的:
(define (write-to-file path string-list)
(call-with-output-file path
(lambda (output-port)
(write <???> output-port)))) ; how do you want to write string-list ?
当然,在上面的过程中你可以摆弄
lambda
的主体。从字符串列表中生成您期望的输出,例如 - 作为字符串列表,或每行中的字符串,或作为具有一系列由空格分隔的字符串等的单行。您将调用两个程序都是这样的:(write-to-file "/path/to/output-file"
(check input))
关于scheme - 写出到方案中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10467202/