I'm trying to simplify the below code that's part of an attoparsec parser for a network packet, and I'm at a loss for a nice way to do it.
It starts with a call to atEnd :: IO Bool
to determine if there's more to parse. I can't find a nicer way to use atEnd
than to unwrap it from IO and then use it in an if statement, but it seems like there must be be a simpler way to check bool inside a monad. Here's the code:
maybePayload :: Parser (Maybe A.Value)
maybePayload = do
e <- atEnd
if e then return Nothing
else do
payload' <- char ':' *> takeByteString
maybe mzero (return . Just) (maybeResult $ parse A.json payload')
The intention is to return Nothing
if there is no payload, to return Just A.Value
if there is a valid JSON payload, and for the parser to fail if there is a non-valid payload.
Here's the Packet record that eventually gets created:
data Packet = Packet
{ pID :: Integer
, pEndpoint :: String
, pPayload :: Maybe A.Value
}