user38352
user38352

Reputation: 85

How does Haskell determine what kind of boolean a randomly generated number is?

Consider the following two groups of code:

random (mkStdGen 1) :: (Int, StdGen) 
-- returns (7918028818325808681,545291967 2103410263)
random (mkStdGen 1) :: (Bool, StdGen) 
-- returns (True,80028 40692)


random (mkStdGen 949488) :: (Int, StdGen) 
-- returns (9159618695640234475,587416689 2103410263)
random (mkStdGen 949488) :: (Bool, StdGen)
-- returns (False,1485632275 40692)

Why does 7918028818325808681 translate to True but 9159618695640234475 translates to False?

Upvotes: 1

Views: 114

Answers (1)

Joachim Breitner
Joachim Breitner

Reputation: 25782

The Instance Bool shares the implementation with Instance Int, but the code that is shared is the one for randomR, which takes a range. We can verify this using QuickCheck:

Prelude> import Test.QuickCheck
Prelude Test.QuickCheck> import System.Random
Prelude Test.QuickCheck System.Random> :{
Prelude Test.QuickCheck System.Random| prop seed = let
Prelude Test.QuickCheck System.Random|   gen = mkStdGen seed
Prelude Test.QuickCheck System.Random|   b = fst (random gen)
Prelude Test.QuickCheck System.Random|   i = fst (randomR (0,1) gen)
Prelude Test.QuickCheck System.Random|  in if b then i == 1 else i == 0
Prelude Test.QuickCheck System.Random| :}
Prelude Test.QuickCheck System.Random> quickCheck prop
+++ OK, passed 100 tests.

You can also look at the definition of the instance Random Bool where you will find this code:

instance Random Bool where
  randomR (a,b) g = 
      case (randomIvalInteger (bool2Int a, bool2Int b) g) of
        (x, g') -> (int2Bool x, g')
       where
         bool2Int :: Bool -> Integer
         bool2Int False = 0
         bool2Int True  = 1

     int2Bool :: Int -> Bool
     int2Bool 0 = False
     int2Bool _ = True

  random g    = randomR (minBound,maxBound) g

so essential, you are calling randomR (0,1) and then mapping 0 to False and 1 to True:

> random (mkStdGen 949488) :: (Bool, StdGen)
(False,1485632275 40692)
> randomR (0,1) (mkStdGen 949488) :: (Int, StdGen)
(0,1485632275 40692)
> random (mkStdGen 1) :: (Bool, StdGen)
(True,80028 40692)
> randomR (0,1) (mkStdGen 1) :: (Int, StdGen)
(1,80028 40692)

Upvotes: 8

Related Questions