0

比如说我有

(define sample '("a" "b" "c"))

我将如何创建一个可以与示例一起使用的嵌套循环。

 (define (runthis a)
    (cond
    (char? (car a)) ;given that this condition is true I go on to the nested loop

    (define (work sample)
    <dosomething>
    (work (cdr sample))))

    (else (write " ")
(runthis(cdr a)))) 

这是基本嵌套循环的正确模板吗?

4

3 回答 3

3

如果您需要嵌套循环,我建议使用 for 代替。这是一个小而愚蠢的例子。外部循环一次遍历列表中的单词。如果当前单词以 r 开头,则内部循环将一次打印每个字符。

#lang racket

(define (print-words-beginning-with-r words)
  (for ([word words]
        #:when (char=? (string-ref word 0) #\r))
    (for ([c word])
      (display c))
    (newline)))

(print-words-beginning-with-r '("racket" "rocks" "!"))

这输出

racket
rocks
于 2012-05-07T20:10:19.983 回答
1

我没有方便的 Scheme 解释器,但它看起来不会运行。

我不确定您所说的“嵌套循环”究竟是什么意思,或者您试图满足什么要求,但在 Scheme 中不鼓励使用大量嵌套和长函数,因为它们会影响可读性/清晰度。您是否试图复制这种行为?

while(foo) {
    while(bar) {
        // Frob the fizzbits
    }
}

我会推荐这样的东西,它在功能上是等效的,但更容易理解:

(define (inner-loop the-list)
  ; do things
)

(define (outer-loop the-list)
  (cond (char? (car a)) (inner-loop the-list)
        (else           (write " "))))
于 2012-05-07T16:47:47.187 回答
1

另一种可能性是 named let,如:

(define (runthis a)
  (cond
    ((char? (car a))
     (let loop ((sample a))
       (cond 
         ((null? sample) '())
         (else (display (car sample))
           (loop (cdr sample))))))
    (else (write " "))))
于 2012-05-07T16:57:40.580 回答