[Haskell-cafe] mixing wxhaskell state and file io

Donald Bruce Stewart dons at cse.unsw.edu.au
Sun Feb 4 18:17:17 EST 2007


martindemello:
> I'm having a lot of trouble mixing file io and wxhaskell's
> varCreate/Get/Set functions. I have functions
> 
> readWords :: String -> IO WordMap
> wordGrid :: WordMap -> Layout
> 
> And within my GUI code, the following compiles (ignores the variable,
> basically):
> 
> words  <- varCreate (do {w <- readWords "words"; return w})
> wGrid  <- do w <- readWords "words"
>                    return $ wordGrid w
> 
> but I can't get the following (noncompiling code, but it shows what
> I'm trying to do) working:
> 
> wGrid  <- do w <- varGet words
>                    return $ wordGrid w
> 
> Could someone give me a minimal example of reading in a list of words
> from a file, binding a wxHaskell variable to the list, and then
> mapping some GUI code over it?

Here's an efficient read-words-from-file function:

    $ cat A.hs
    import qualified Data.ByteString.Char8 as S (words,readFile)
    import Data.ByteString       (ByteString)

    getWords :: FilePath -> IO [ByteString]
    getWords f = fmap S.words (S.readFile f)

    main = print . length =<< getWords "/usr/share/dict/words"

    $ time ./A
    234979
    ./A  0.09s user 0.01s system 94% cpu 0.107 total

If you wanted to turn this list of words into a Map, something like:

    buildMap :: [ByteString] -> M.Map ByteString Int
    buildMap xs = M.fromListWith (+) (zip xs (repeat 1))

(untested).

As for wxHaskell, I'll have to defer to the ui hackers for that.

-- Don


More information about the Haskell-Cafe mailing list