Generate a random integer in a range in Haskell without a seed

前端 未结 5 1306
自闭症患者
自闭症患者 2020-12-14 08:52

How can I generate a random number in Haskell from a range (a, b) without using any seed?

The function should return an Int and not an IO Int. I have a function X t

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 09:15

    fmap yourFunctionX $ randomRIO (a, b)
    

    or

    fmap (\x -> yourFunctionX aParam x anotherParam) $ randomRIO (a, b)
    

    The result will then be of type IO whateverYourFunctionXReturns.

    If you import Control.Applicative, you can say

    yourFunctionX <$> randomRIO (a, b)
    

    or

    (\x -> yourFunctionX aParam x anotherParam) <$> randomRIO (a, b)
    

    which you may find clearer

提交回复
热议问题