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

前端 未结 5 1301
自闭症患者
自闭症患者 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:14

    Note that you can get an infinite list of random values using the IO monad and use that [Int] in non-IO functions. This way you don't have to carry the seed along with you, but still need to carry the list of course. Fortunately, there are plenty of list processing functions to simplify such threading, and you can still use the State monad in complicated cases.

    Also note that you can easily convert an IO Int to an Int. If foo produces an IO Int, and bar takes an Int as its only parameter and returns a non-IO value, the following will do:

    foo >>= return . bar
    

    Or using do notation:

    do 
        a <- foo
        return $ bar a
    

    Or using fmap (monads are functors, and <$> is an infix version of fmap):

    bar <$> foo
    

提交回复
热议问题