samedi 9 janvier 2016

Getting random numbers from non-monadic functions

So my goal is to be able to call a non-monadic function and have it return a random value.

getNums :: [Int] -- this only works when the type signature is "IO [Int]"
getNums = getListFromIO 10

getListFromIO :: Int -> IO [Int]
getListFromIO n = do
  gen <- newStdGen
  return $ generateList n gen

generateList :: Int -> StdGen -> [Int]
generateList n gen = take n $ randomRs (1,9) $ gen

If I call getListFromIO, all is well; I get my precious random list of integers, and it is different every time. But every function that calls it must use IO [Int] it the type signature. I don't want that.

How can I structure this so that I am able to get a random number list of type [Int]?




Aucun commentaire:

Enregistrer un commentaire