[Haskell-cafe] How to select n random words from a file ...

Alexander Solla alex.solla at gmail.com
Mon Jun 11 07:12:40 CEST 2012

On Sun, Jun 10, 2012 at 6:21 AM, Noon Silk <noonslists at gmail.com> wrote:

> Hi,
>  I'm clearly new to haskell, and I suppose those is a basic question,
> but after a bit of searching I've been unable to figure out the "best"
> way to do this. I was first trying to find out how to, say, get a
> random element from a list, but I'm starting to think that may not be
> the best way (because list access isn't constant time, among other
> reasons). So, I wonder if there is a more direct way to just get a
> random word from a wordfile (i.e. one word per line) ... can anyone
> suggest a method?

My preferred option, assuming the file sizes make it amenable, is to use
Iteratees to fold the wordlists into an IntMap of words.  You can then take
the size of the map and choose n unique Ints in the range.

Note that any algorithm is going to include these basic steps. (Get the
size, pick randoms, access the words at the key/line number).  The most
direct approach would basically be imperative and in the IO monad, using
things like openFile and hSeek.

This approach gets harder if you want to pull words out of multiple
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120610/f8ad339b/attachment.htm>

More information about the Haskell-Cafe mailing list