[Haskell-cafe] Comments on reading two ints off Bytestring

Bryan O'Sullivan bos at serpentine.com
Sun Dec 23 09:45:03 EST 2007

Paulo J. Matos wrote:

> I guess the latter is the correct guess.

Good guess!

You can take advantage of the fact that the Maybe type is an instance of
the Monad typeclass to chain those computations together, getting rid of
all of the explicit case analysis.

import qualified Data.ByteString.Char8 as B
import Data.Char (isDigit)

readTwoInts :: B.ByteString -> Maybe ((Int, Int), B.ByteString)
readTwoInts r = do
  (a, s) <- B.readInt . B.dropWhile (not . isDigit) $ r
  (b, t) <- B.readInt . B.dropWhile (not . isDigit) $ s
  return ((a, b), t)

Let's try that in ghci:

  *Main> readTwoInts (B.pack "hello 256 299 remainder")
  Just ((256,299)," remainder")

The case analysis is still happening, it's just being done behind your
back by the (>>=) combinator, leaving your code much tidier.  (And why
is there no explicit use of (>>=) above?  Read about desugaring of "do"
notation in the Haskell 98 report.)

The learning you'll want to do, to be able to reproduce code such as the
above, is about monads.



More information about the Haskell-Cafe mailing list