I have a Request
type:
data Request =
Request {
reqType :: RequestType,
path :: String,
options :: [(String, String)]
} deriving Show
And I'm parsing it (from a raw HTTP
request), as follows:
parseRawRequest :: String -> Request
parseRawRequest rawReq =
Request {
reqType = parseRawRequestType rawReq,
path = parseRawRequestPath rawReq,
options = parseRawRequestOps rawReq
}
Now, the calls to parseRawRequestType
, parseRawRequestPath
(etc) can fail. To make my code more resilient, I've changed their type signature from:
parseRawRequestType :: String -> RequestType
to
parseRawRequestType :: String -> Maybe RequestType
But what is the best way to turn parseRawRequest
into a Maybe Request
? Do I have to manually check each component (reqType
, path
, options
) for Nothing
, or is there a different way that I'm missing?
There must be a way to somehow compose the object creation and Nothing
-checking!
I wrote the following, but it feels messy and not ideal: (Untested)
parseRawRequest :: String -> Maybe Request
parseRawRequest rawReq
| Nothing `elem` [reqType, path, options] = Nothing
| otherwise =
Just Request { reqType=reqType, path=path, options=options }
where reqType = parseRawRequestType rawReq
path = parseRawRequestPath rawReq
options = parseRawRequestOps rawReq
Cheers.