0

Say I have for example

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

How would I go about creating a nested loop that will work with sample.

 (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)))) 

is this the correct template for a basic nested loop?

3 Answers 3

3

If you need nested loops, I recommend using for instead. Here is a small, silly example. The outer loops runs through the words in the list one at a time. If the current word begins with an r, then the inner loop will print each character one at a time.

#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" "!"))

This outputs

racket
rocks
Sign up to request clarification or add additional context in comments.

Comments

1

I don't have a Scheme interpreter handy, but that doesn't look like it'll run.

I'm not sure what exactly you mean by "nested loop," or what requirement you're attempting to satisfy, but lots of nesting and long functions are discouraged in Scheme because they impact readability/clarity. Are you trying to replicate this sort of behavior?

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

I would recommend something like this, which is functionally equivalent but easier to grok:

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

(define (outer-loop the-list)
  (cond (char? (car a)) (inner-loop the-list)
        (else           (write " "))))

1 Comment

This helped. THank you Torgamus!
1

Another possibility would be the named let, as in:

(define (runthis a)
  (cond
    ((char? (car a))
     (let loop ((sample a))
       (cond 
         ((null? sample) '())
         (else (display (car sample))
           (loop (cdr sample))))))
    (else (write " "))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.