这样做的目的是检查所考虑的字符是数字还是操作数,然后将其输出到列表中,该列表将写入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)))
我想到的另一个问题是,如何才能使检查过程递归? 我知道这很多问题,但是我在查看我在其他网站上找到的方法时感到有点沮丧。 我非常感谢你的帮助!
答案 0 :(得分:3)
最好将功能分成两个独立的过程,一个用于生成字符串列表,另一个用于将它们写入文件。对于第一个程序,我会给你一般的想法,所以你可以填写空白(毕竟这是一个功课),它遵循递归解决方案的标准结构:
(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))