neham
neham

Reputation: 341

how to create nested loop in scheme

I am new to scheme and I am trying to create nested loops whose code in C will look like this:-

for(i = -1, a = 0; i > -5, a < 5; i--, a++)
{ 
   for(j = i, b = 0; j < (abs(i)), b < 5; j++, b++)
   { 
      <do something>
   }
}

I tried similar thing in scheme with this concept:-

(let oloop( (i -1) (a 0))
            (display i)(display a) (newline) 
            (if (and (> i -5) (< a 5)) (oloop((- i 1) (+ a 1))))))

I am not able to nest all four loops plus above code is not working.

Please suggest.

Upvotes: 1

Views: 2213

Answers (3)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

If you're using Racket, there's a pretty straightforward way to implement C-style loops, using iterations and comprehensions. The code looks almost the same:

(for [(i (in-range -1 -5 -1))
      (a (in-range 0 5))]
  ; body of the outer loop
  ; do something with i a
  (for [(j (in-range i (abs i)))
        (b (in-range 0 5))]
    ; body of the inner loop
    ; do something with i a j b
    (display (list i a j b))))

Upvotes: 0

Terje D.
Terje D.

Reputation: 6315

One way to write these nested loops is to use to do looping construct, which takes 3 arguments: The variables to bind (with initial value, and update forms), the termination condition, and the body forms:

(do ((i -1 (- i 1))                ; Count i downwards from -1
     (a  0 (+ a 1)))               ; Cound a upwards from 0
    ((or (= i -5) (= a 5)))        ; Stop when i = -5 or a = 5
  ;; Body of outer loop
  (do ((j i (+ j 1))               ; Count j upwards from i
       (b 0 (+ b 1)))              ; Count b upwards from 0
      ((or (= (abs i) j) (= b 5))) ; Stop when j = abs(j) or b = 5
    ;; Body of inner loop: Do something
    ))

If you insist of doing it by recursion, using named lets, it can be done like this, having the drawback that the forms updating the variables are located far away from the initialization and termination forms:

(let outer ((i -1) (a 0))
  (if (and (> i -5) (< a 5))
      (begin
        (let inner ((j i) (b 0))
          (if (and (< j (abs i)) (< b 5))
              (begin
                ; Do something
                ; then loop
                (inner (+ j 1) (+ b 1)))))
        (outer (- i 1) (+ a 1)))))

Upvotes: 8

Stephan Branczyk
Stephan Branczyk

Reputation: 9375

Where is the equivalent of i-- in your Scheme sample?

(+ i 1)

I'm a bit rusty on my Scheme, but I don't think that's it.

Also, I'm not sure where you're getting this base case from in your C program?

(< i 10)

Upvotes: 0

Related Questions