4

这样做的目的是检查所考虑的字符是数字还是操作数,然后将其输出到一个列表中,该列表将被写入一个 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)))

我想到的另一个问题是,我怎样才能使检查过程是递归的?我知道这要求很多,但我对查看我在其他网站上找到的方法感到有点沮丧。我真的很感激帮助!

4

1 回答 1

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))
于 2012-05-06T05:36:11.650 回答