
I have this function: -- | Choose an element at random from a list and return the element and its index -- Ex: runState (randomListSelection ['a', 'b', 'c', 'd', 'e']) (mkStdGen 1) randomListSelection :: (RandomGen s) => [a] -> State s (Int, a) randomListSelection xs = do i <- State $ randomR (0,length xs - 1) return (i, xs !! i) I want to repeatedly select random elements from a list. I know the code below is totally wrong, but it's the closest I've gotten so far. When I run it in ghci, I get the SAME random element each time, until I reload the module. I guess that's because g is always the same. I'm still struggling with monads, and would appreciate any advice on how to fix this. chooseCreatur = do g <- getStdGen return (evalState (randomListSelection ["cat", "dog", "lion", "mouse"]) g) FWIW, I'll be calling it from a loop within the IO monad. The real list will be growing and shrinking in size.

Does this help?
http://www.haskell.org/haskellwiki/99_questions/Solutions/24
-deech
On Tue, Nov 16, 2010 at 6:13 PM, Amy de Buitléir
I have this function:
-- | Choose an element at random from a list and return the element and its index -- Ex: runState (randomListSelection ['a', 'b', 'c', 'd', 'e']) (mkStdGen 1) randomListSelection :: (RandomGen s) => [a] -> State s (Int, a) randomListSelection xs = do i <- State $ randomR (0,length xs - 1) return (i, xs !! i)
I want to repeatedly select random elements from a list. I know the code below is totally wrong, but it's the closest I've gotten so far. When I run it in ghci, I get the SAME random element each time, until I reload the module. I guess that's because g is always the same. I'm still struggling with monads, and would appreciate any advice on how to fix this.
chooseCreatur = do g <- getStdGen return (evalState (randomListSelection ["cat", "dog", "lion", "mouse"]) g)
FWIW, I'll be calling it from a loop within the IO monad. The real list will be growing and shrinking in size.
_______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners

aditya siram
Does this help? http://www.haskell.org/haskellwiki/99_questions/Solutions/24 -deech
Indeed it does, thank you deech. For the benefit of anyone who googles this, here's a solution that works. import "mtl" Control.Monad.State import System.Random -- | Choose an element at random from a list and return the element and its index randomListSelection :: [a] -> IO (Int, a) randomListSelection xs = do i <- randomRIO (0,(length xs)-1) return (i, xs !! i) chooseCreatur :: IO (Int, [Char]) chooseCreatur = randomListSelection ["cat", "dog", "lion", "mouse"]

Amy de Buitléir
participants (2)
-
aditya siram
-
Amy de Buitléir