Haskell Grokking random number generation

I have a function probabilities :: String -> [(String, Double)]that returns a probability distribution based on input String. Now I want to create a new random Stringone based on this probability distribution with a function similar generate :: String -> String. I recently found fromListin Control.Random.Monad, but I'm afraid to use it for my specific situation. Can someone help me in the right direction? If you need more information, please ask.

Additional Information:

I need to be called multiple times generatefor use in another algorithm.

+3
source share
1 answer

You will need monads. Let me change the type generateto:

generate :: (MonadRandom m) => String -> m String

generate, :

generate = fromList . probabilities

generate foo :

iterateM ( monad-loops)

iterateM :: Monad m => Int -> (a -> m a) -> a -> m a
iterateM 0 _ a = return a
iterateM n f a = f a >>= iterateM (n-1) f
  • Foo :

    foo :: (MonadRandom m) => String -> m String
    foo = iterateM 10 generate
    
  • foo pure:

     foo :: Int -> String -> String
     foo seed str = evalRand (iterateM 10 generate str) (mkStdGen seed)
    
+3

All Articles