2
votes

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.

1
((set! result (random y)) ...) is nonsensical. Why not just use let? - leppie
My keyboard is broken and I can't type "L" without using telekinesis to change the bits in the RAM. Or maybe we all start somewhere. - Theodor Berza
I dont know what you saying, but a double parenthesis is generally a place of concern unless it evaluates to a procedure. In your case, set! will never do that. - leppie
I didn't knew the difference between set and let until 1 hour ago. - Theodor Berza
We all learn, but learning the hard way, sticks forever :D - leppie

1 Answers

3
votes

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