Theodor Berza
Theodor Berza

Reputation: 583

set! Unbound identifier in module ERROR in Racket

I try to write a function that returns a random number between the first and the second argument.

(random-between 40 80)

Should give a random number between 40 and 80. Here is the code:

(define (random-between x y)
   ((set! result (random y))
        (if (> result x)
            result
            (random-between x y))))

I suppose when the function runs recursively the second time, the random function creates a new result who is again tested and if it is above x it is output as the final result.

This is the first time I use "set!" and it gives me this error:

set!: unbound identifier in module in: result

The other similar questions didn't help me find a solution.

Upvotes: 3

Views: 2149

Answers (1)

Theodor Berza
Theodor Berza

Reputation: 583

I will answer my own question as I would have wished for others to answer it. Not snarky answers or book recommendations.

Yes, you need to use let which has this syntax:

(let ([id value]) body-which-is-evaluated-after)

And this is the code that has no recursion for speed efficiency.

(define (random-between x y)
    (let ([result (- y x)]) 
         (+ (random result) x)))

Upvotes: 4

Related Questions