sicp-lang/sicp

random: unbound identifier in module

HiPhish opened this issue · 8 comments

I'm trying to do exercise 3.5 and it makes use of the random procedure, which is apparently not provided by the SICP language. It is provided by the racket language though.

Hi HiPhish,

You can use #%require to import identifiers from other languages such as Racket.

#lang sicp
(#%require (only racket random))
(random 5)

I agree that the sicp language should provide random.
This will eventually be added.

If you find other missing identifiers, please alert us.

/Jens Axel

If you find other missing identifiers, please alert us.

Sure thing. The Racket implementation of random seems to be different from what's described in the book though:

If you're using Racket the random function doesn't work as described in the text. You might want to use this instead:

(define (random-in-range low high) 
   (let ((range (- high low))) 
     (+ low (* (random) range)))) 

http://community.schemewiki.org/?sicp-ex-3.5

That had me hung up for quite a while on the exercise before I decided to look up the solution.

The SICP random picks its return type automatically:

MIT Scheme provides such a procedure. If random is given an exact integer (as in Section 1.2.6) it returns an exact integer, but if it is given a decimal value (as in this exercise) it returns a decimal value.

The exercise is about picking random points (x- and y coordinates) inside a rectangle. We are trying to compute the value of π using a unit circle inside the rectangle, so the return value of random should be a real number instead of an integer. Would this work?

(define (sicp-random n)
  (if (exact? n)
    (random n)
    (* n (random))))

I'm not very familiar with Racket's intricacies, I have only been using it for SICP.

Yes, you sicp-random function should work fine.
To make sure the input is an exact integer you could add (integer? n):

(define (sicp-random n)
  (if (and (exact? n) (integer? n))
      (random n)
      (* n (random))))

@soegaard Nice. What part of the Racket documentation should I read in order to add that function to the language?

I also noticed there is no error function either. Should I open a new issue?

Is there a plan to add random to this racket package?

As a novice to SICP, I found the random procedure was first mentioned in subsection "The Fermat test" of Sec 1.2.6.

The doc introduces random in MIT/GUN Scheme can be found here.

@muzimuzhi

I just added random.