随机选择并填充数据类型

时间:2012-07-29 18:52:53

标签: haskell

所以我有两种数据类型。为简单起见,一个人持有Int,一个持有String

所以让我说我有

data ranData = randInt Int | randString String

如何创建一个能够选择其中一个然后给它一个随机值的函数。我有一些想法,但它们相当不优雅。

2 个答案:

答案 0 :(得分:2)

QuickCheck的Arbitrary class有一些useful functions

您的任意实例看起来与预定义的Either实例相同:

instance (Arbitrary a, Arbitrary b) => Arbitrary RanData where
  arbitrary = oneof [liftM RandInt arbitrary, liftM RandString arbitrary]

  shrink (RandInt x)  = [ RandInt  x' | x' <- shrink x ]
  shrink (RandString y) = [ RandString y' | y' <- shrink y ]

答案 1 :(得分:1)

假设您要使用MonadRandom包:

import Data.Functor ((<$>))
import Control.Monad.Random

data RanData = RandInt Int | RandString String deriving Show

randomData :: (RandomGen g) => Rand g RanData
randomData = do
  shouldBeString <- getRandom -- Generate Bool
  if shouldBeString
    then do
      len <- getRandomR (0, 10) -- Generate Int between 0 and 10
      RandString . take len <$> getRandoms -- Take between 0 and 10 random chars
    else RandInt <$> getRandom -- Generate random Int

-- How to use:
main :: IO ()
main = print =<< evalRandIO randomData -- There are many other ways, too

randomData函数会在RanData monad中生成Rand,并带有一些随机数生成器gevalRandIO函数将使用RanData随机数生成器提取随机StdGen。还有许多其他随机数生成器和运行它们的方法;这只是一个例子。