DiegoEwin
DiegoEwin

Reputation: 11

Recursivity in Racket to create a list of coordinates

I want to create a function that returns a list of coordenates in the for of pairs such as: (0.0) (0.1)...(rows.columns). It goes to an infinite loop and i don't know why. Any suggestion?

(define (generate-positions-rec rows columns)
  (cond [(and (= rows 0) (= columns 0)) empty]
        [else (cons rows columns)
              (generate-positions-rec (- rows 1)(- columns 1))]
        ))

Upvotes: 0

Views: 68

Answers (1)

Óscar López
Óscar López

Reputation: 236122

Your code will go into a recursive loop if it's invoked with a negative number or one of the parameters is greater than the other. We can fix this issue with a proper base case.

But you're not actually building a list as output, the call to cons is lost. This is what you meant to do, notice how you need to cons the new pair of coordinates to the result of the recursive call:

(define (generate-positions-rec rows columns)
  (cond [(or (<= rows 0) (<= columns 0)) empty]
        [else (cons (cons rows columns)
                    (generate-positions-rec (- rows 1)(- columns 1)))]))

This is how it works now:

(generate-positions-rec 4 3)
=> '((4 . 3) (3 . 2) (2 . 1))

Upvotes: 1

Related Questions