[Haskell-cafe] How to use Data.ByteString ?

Thomas DuBuisson thomas.dubuisson at gmail.com
Tue May 19 01:20:52 EDT 2009

On Mon, May 18, 2009 at 10:13 PM, Brandon S. Allbery KF8NH
<allbery at ece.cmu.edu> wrote:
> On May 19, 2009, at 01:07 , z_axis wrote:
> rollDice_t n = do
>     hd <- openFile "/dev/random" ReadMode
>     v <-  B.hGet hd 1
>     return (v `mod` n) + 1
>  No instance for (Integral B.ByteString)
> You can't just read a binary string and have it interpreted as a number; you
> want to use Data.Binary to extract an Int (or whatever) from the ByteString.
>  The same would apply with legacy Strings; in Haskell, String, ByteString,
> and Int are distinct types and there is no automatic casting.  In fact I'm
> not quite sure why you thought that should work; even Perl would make you
> unpack(), and C would require you to use an appropriately-aligned buffer and
> unsafely cast the (char *) to an (int *).

More so, you appear to only be getting one byte from your random
number source, so that really limits the range of numbers this
function can produce.

Also, the error you are getting is more to do with ambigious types
because there is a typeclass implied and you didn't add any type
annotations yourself.

1) Use Data.ByteString.Lazy
2) Read the file, and don't forget to close it - or rework how you
intend to get randoms (a better solution!)
3) Use 'decode' form Data.Binary and add a type signature to get an
Int, Word32, or some such.
4) Apply mod and return


More information about the Haskell-Cafe mailing list