Ricky Han
Ricky Han

Reputation: 1367

How to use random numbers within recursion?

I'm trying to select a random element from a list but that'll make the function impure thus fail to compile. What should I do to make the recursive function accept an IO action?

build :: Jabberwocky Integer String Syllables -> String
build (Jabberwocky 0 body syl) = body
build (Jabberwocky len body syl)
    | syl == Middle     = build (Jabberwocky (len - 1) (body ++ (rand middle)    ) Consonant)
    | syl == Consonant  = build (Jabberwocky (len - 1) (body ++ (rand consonant)) Vowel)
    | syl == Vowel      = build (Jabberwocky (len - 1) (body ++ (rand vowel)     ) Consonant)
    | syl == Ending     = build (Jabberwocky (len - 1) (body ++ (rand ending)    ) Vowel)
        where 
            rand = getStdRandom (randomR (1,6))

Upvotes: 3

Views: 505

Answers (1)

josejuan
josejuan

Reputation: 9566

You must carry generator into pure process (chaining new random generator state)

randomR_nTimes_rec :: (RandomGen g, Random a) => Int -> (a, a) -> g -> ([a], g)
randomR_nTimes_rec 0 _ g = ([], g)
randomR_nTimes_rec n i g = (x:xs, g'') where ( x, g' ) = randomR i g
                                             (xs, g'') = randomR_nTimes_rec (n - 1) i g'

usage

*Main> getStdGen  >>= return . randomR_nTimes_rec 5 (0,5)
([2,5,3,1,3],1206240749 652912057)

if you should carry random state into a complex process may be useful Control.Monad.Random with example

Upvotes: 2

Related Questions