Pick random element

From Rosetta Code
Revision as of 15:39, 9 August 2011 by rosettacode>Mcandre (Added Haskell and Smalltalk)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Pick random element is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

How does one pick a random element from a list?

Haskell

Creating a custom function:

<lang haskell>import Random (randomRIO)

pick :: [a] -> IO a pick xs = randomRIO (0, length xs - 1) >>= return . (xs !!)

x <- pick [1 2 3]</lang>

Using the random-extras library:

<lang haskell>import Data.Random import Data.Random.Source.DevRandom import Data.Random.Extras

x <- runRVar (choice [1 2 3]) DevRandom</lang>

Smalltalk

<lang smalltalk>st> #(1 2 3) atRandom.</lang>