[Haskell-cafe] Comments on reading two ints off Bytestring
conal at conal.net
Mon Dec 24 19:13:36 EST 2007
To clean up even more, use StateT B.ByteString Maybe. Then the ByteString
threading will be invisible, leading to just "liftM2 (,) readI readI", for
suitably defined readI.
On Dec 23, 2007 6:45 AM, Bryan O'Sullivan <bos at serpentine.com> wrote:
> 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.
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe