walter
walter

Reputation: 193

Random element from list Haskell

I'm trying to get a random Int from a list and I'm having some issues because the only libraries that we're allowed to use are QuickCheck, GHC.IO and Data.List.

So far I managed to get a random IO Int by using:

ran :: Gen Int
ran = choose (0,3) 

(The list has length=4)

But when I call

elem = list !! generate ran

I get: Couldn't match expected type ‘Int’ with actual type ‘IO Int’ And i'm pretty sure you can't "extract" only the Int from an IO Int so i'm kinda lost.

¿Any ideas?

Upvotes: 2

Views: 270

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477883

You can work with an fmap such that elem is an IO Int:

elem :: IO Int
elem = fmap (list !!) (generate ran)

or we can work with the operator alias of fmap: (<$>):

elem :: IO Int
elem = (list !!) <$> generate ran

It is probably better, as @AndrewRay says, to use another name, since the Prelude already contains an elem function. For example randElem:

randElem :: IO Int
randElem = (list !!) <$> generate ran

Upvotes: 3

Related Questions