Random doubles

Marcin 'Qrczak' Kowalczyk qrczak@knm.org.pl
14 Feb 2001 18:36:15 GMT


Wed, 14 Feb 2001 16:25:04 +0000, andrew@andrewcooke.free-online.co.uk <andrew@andrewcooke.free-online.co.uk> pisze:

> Could someone please post a fragment of code that builds a list of
> random Doubles using RandomIO (recursively, please, although an
> example of using the interface that gives lists of random values
> directly would also be interesting)?

Doubles from which range? Assuming (0,1) and that the Int means the
length of the list:

import Random
import Monad

rands1:: Int -> IO [Double]
rands1 0 = return []
rands1 n = do
    x <- randomIO
    rest <- rands1 (n-1)
    return (x:rest)

rands2:: Int -> IO [Double]
rands2 0 = return []
rands2 n = liftM2 (:) randomIO (rands1 (n-1))

rands3:: Int -> IO [Double]
rands3 n = sequence (replicate n randomIO)

rands4:: Int -> IO [Double]
rands4 n = do
    g <- newStdGen
    return (take n (randoms g))

-- 
 __("<  Marcin Kowalczyk * qrczak@knm.org.pl http://qrczak.ids.net.pl/
 \__/
  ^^                      SYGNATURA ZASTĘPCZA
QRCZAK