List of random doubles within a specific range in Haskell?

How can I make a list of random numbers like "Double" that correspond to a certain range? Information on this for a novice like me is a bit confusing. Try something like:

randomlist :: Int -> Int -> [IO Double]
randomlist a b = do
  g <- newStdGen
  return (randomRs (a,b) g)

with an error:

Couldn't match expected type `[t0]' with actual type `IO StdGen'

Could you point out the errors in my code?

+5
source share
2 answers

. . - [IO Double] ; , -, . IO [Double] — IO, . , ; , a b Int s, return Double s. , . ( Int Double s, fromIntegral; round.) , , , ,

randomlist :: Double -> Double -> IO [Double]
randomlist a b = do
  g <- newStdGen
  return (randomRs (a,b) g)

, , ; GHC Random a => a -> a -> IO [a]. , , .

. , :

randomlist :: Random a => a -> a -> IO [a]
randomlist a b = fmap (randomRs (a,b)) newStdGen

fmap :: Functor f => (a -> b) -> f a -> f b . ? , - ; , [], (r ->) IO . 1 , ; randomRs (a,b) (Random a, RandomGen g) => g -> [a], - IO StdGen, Random a => IO [a] .

( ). Control.Applicative,

import Control.Applicative
randomlist :: Random a => a -> a -> IO [a]
randomlist a b = randomRs (a,b) <$> newStdGen

<$> fmap; $, , . <$> ( IO).


1: , ; , , .

+7

. ghci , :

*Main> :t randomlist
randomlist :: Random a => a -> a -> IO [a]

, Double -> Double -> IO [Double], , fromIntegral, :

randomlist :: Int -> Int -> IO [Double]
randomlist a b = do
    g <- newStdGen
    return (randomRs (fromIntegral a, fromIntegral b) g)

[IO Double] IO [Double]. - , Double, - , Double, .

, , , newStdGen IO StdGen, <- , do - IO something, , [something].

+7

All Articles