samedi 7 septembre 2019

How can I generate different random values in Haskell?

Suppose that I have a list like this:

let list = ["random", "foo", "random", "bar", "random", "boo"]

I want to iterate over a list and map all "random" elements to different random strings:

let newList = fmap randomize list
print newList
-- ["dasidias", "foo", "gasekir", "bar", "nabblip", "boo"]

My randomize function looks like this:

randomize :: String -> String
randomize str = 
  case str of
    "random" -> randStr
    _        -> str
  where
    randStr = take 10 $ randomRs ('a','z') $ unsafePerformIO newStdGen

But I get the same random string for every "random" element:

["abshasb", "foo", "abshasb", "bar", "abshasb", "boo"]

I can't figure out why is this happening and how to get a different random value for each occurrence of "random".




Aucun commentaire:

Enregistrer un commentaire