Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

haskell - How to pick a random list element in a pure function?

I want to make a Haskell function that can pick out a random number from a given list. My type signature is:

randomPick :: [a] -> a 

What should I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Part of the definition of a "pure" function in Haskell is that it is referentially transparent, that is, interchangeable with the result of evaluating it. This implies that the result of evaluating it must be the same every time. Ergo, the function you want isn't possible, I'm afraid. To generate random numbers in Haskell, a function needs to do one of two things:

Take and return a pseudorandom number generator, e.g.:

randomPick :: RNG -> [a] -> (a, RNG)

Or use IO to access randomness from "the outside world":

randomPick :: [a] -> IO a

Both styles are provided by the module System.Random. Also, in the former case, passing the PRNG around can be abstracted out using the State monad, or perhaps a special-purpose Random monad.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...