dimanche 20 novembre 2016

Using random values obtained from the global random number generator in Haskell in arithmetic and logic operations

How do you use IO Double values obtained from the global random number generator in Haskell in arithmetic and logic operations? Most tutorials on the internet focus on obtaining random numbers, but somehow I seem not to be able to do something useful with them.

The following code contains some function test containing some of the operations I want to perform.

{-# LANGUAGE Strict #-}
module RNG where
import System.Random(setStdGen, mkStdGen, randomRIO)

seed_rng :: Int -> IO()
seed_rng seed = (setStdGen (mkStdGen seed))

uniform_float :: IO Double
uniform_float = (randomRIO (0.0, 1.0))

test :: Double -> Double -> IO Double
test a b = let u = (uniform_float)
              in if ((<) (return a) u) then ((+) (return b) u) else (return 2.0)

The test function does not compile since there is no instance for Ord (IO Double) and Num (IO Double).

Note that I can avoid the IO Monad by implementing a random number generator and tracking+passing the state myself. But I rather learn to work with Monads instead of always trying to run away from them.




Aucun commentaire:

Enregistrer un commentaire