Using one random variable multiple times in Haskell
It'd like to make a random sequence of opening braces and a matching sequence of closing braces. Here's my (partial) code:
shuffle :: [a] -> IO [a]
ps xs ys 开发者_JAVA技巧= map snd . sort $ zip xs ys
opens = "[{("
closes = "]})"
parens = do
ord <- shuffle [0..length opens]
let os = ps ord opens
cs = reverse $ ps ord closes
It doesn't work since it generates a new ord
for each shuffle. How do I make it remember the ord
and use it for both shuffles?
Don't shuffle them separately.
Shuffle the zip
ped sequence, and unzip
when you're done.
Have you seen Oleg's Provably perfect shuffle algorithms or the System.Random.Shuffle implementation?
Upon rereading your (very incomplete) code, it appears that it could be correct, making some assumptions about the surrounding code. Please show more so we can determine what might be wrong.
As an aside, using map fst . sortBy (comparing `on` fst) . zip xs
or map fst . sortWith fst . zip xs
would more clearly express that your intent is to order one list by another.
精彩评论