[Haskell-beginners] Picking a random element from a Map

Harald Bögeholz bo at ct.de
Wed Sep 26 23:06:54 CEST 2012

Am 26.09.12 10:09, schrieb Daniel Trstenjak:
> Hi Harald,
>> how do I (quickly) pick a random element from a `Data.Map.Map`?

> M.keys map !! randomValue `mod` M.size map
> But if you need a high performance solution than it's more appropriate
> to put the values into a Data.Vector and indexing into it.

I was hoping to find a solution that makes use of the specific structure
of a map, but now I have written it like this and it works for me:

let (r, gen') = randomR (0, Map.size m - 1) gen
in (Map.keys m !! r, gen')

Thanks for the hint!


Harald Bögeholz    <bo at ct.de> (PGP key available from servers)
Redaktion c't      Tel.: +49 511 5352-300  Fax: +49 511 5352-417

                   int f[9814],b,c=9814,g,i;long a=1e4,d,e,h;

                   Affe Apfel Vergaser

/* Heise Zeitschriften Verlag GmbH & Co. KG * Karl-Wiechert-Allee 10 *
   30625 Hannover * Registergericht: Amtsgericht Hannover HRA 26709 *
   Persönlich haftende Gesellschafterin: Heise Zeitschriften Verlag *
   Geschäftsführung GmbH * Registergericht: Amtsgericht Hannover, HRB
   60405 * Geschäftsführer: Ansgar Heise, Dr. Alfons Schräder */

More information about the Beginners mailing list