[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

-- 
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
                   http://www.ct.de/

                   int f[9814],b,c=9814,g,i;long a=1e4,d,e,h;
                   main(){for(;b=c,c-=14;i=printf("%04d",e+d/a),e=d%a)
                   while(g=--b*2)d=h*b+a*(i?f[b]:a/5),h=d/--g,f[b]=d%g;}
                                                          (Arndt/Haenel)

                   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