Haskell如何确定随机生成的数字是什么类型的布尔值?

时间:2017-08-24 17:41:51

标签: haskell random

考虑以下两组代码:

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)

为什么7918028818325808681会转换为True9159618695640234475会转换为False

1 个答案:

答案 0 :(得分:8)

Instance BoolInstance Int共享实现,但共享的代码是randomR的代码,它占用一个范围。我们可以使用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.

您还可以查看definition of the instance Random Bool您将在哪里找到此代码:

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

非常重要,您正在调用randomR (0,1),然后将0映射到False1True

> 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)