| Copyright | (c) 2015 Matthew Leon <ml@matthewleon.com> |
|---|---|
| License | BSD3 |
| Maintainer | creichert07@gmail.com |
| Stability | experimental |
| Portability | portable |
| Safe Haskell | None |
| Language | Haskell2010 |
| Extensions | GeneralizedNewtypeDeriving |
Data.BEncode.Reader
Contents
Description
Reader monad and combinators for BEncoded data.
This is intended to replace the older Data.BEncode.Parser module.
Usage example:
>>>:set -XOverloadedStrings>>>let bd = (BDict $ Map.fromList [("baz", BInt 1), ("foo", BString "bar")])>>>:{let bReader = do baz <- dict "baz" bint foo <- dict "foo" bstring shouldBeNothing <- optional $ dict "optionalKey" bint return (foo, baz, shouldBeNothing) in runBReader bReader bd :} Right ("bar",1,Nothing)
Reader Monad
Reader monad for extracting data from a BEncoded structure.
runBReader :: BReader a -> BEncode -> Either String a #
Run a BReader. See usage examples elsewhere in this file.
Combinators
bbytestring :: BReader ByteString #
Usage same as bstring, below. (sadly, doctests for this cause errors on GHC 7.4)
optional :: Alternative f => f a -> f (Maybe a) #
One or none.
It is useful for modelling any computation that is allowed to fail.
Examples
Using the Alternative instance of Control.Monad.Except, the following functions:
>>>import Control.Monad.Except
>>>canFail = throwError "it failed" :: Except String Int>>>final = return 42 :: Except String Int
Can be combined by allowing the first function to fail:
>>>runExcept $ canFail *> finalLeft "it failed"
>>>runExcept $ optional canFail *> finalRight 42
list :: BReader a -> BReader [a] #
Read a list of BEncoded data
>>>runBReader (list bint) (BList [BInt 1, BInt 2])Right [1,2]
>>>runBReader (list bint) (BList [])Right []
>>>let bs = (BList [BList [BString "foo", BString "bar"], BList []])>>>runBReader (list $ list bstring) bsRight [["foo","bar"],[]]
dict :: String -> BReader a -> BReader a #
Read the values of a BDict corresponding to a string key
>>>let bd = (BDict $ Map.fromList [("bar", BInt 2), ("foo", BInt 1)])>>>runBReader (dict "foo" bint) bdRight 1
>>>:{let bs = (BList [BDict $ Map.fromList [("baz", BInt 2), ("foo", BString "bar")], BDict $ Map.singleton "foo" (BString "bam")]) in runBReader (list $ dict "foo" bstring) bs :} Right ["bar","bam"]
>>>:{let bd = (BDict $ Map.singleton "foo" (BList [ BString "foo", BString "bar" ])) in runBReader (dict "foo" $ list $ bstring) bd :} Right ["foo","bar"]