【发布时间】:2018-07-14 00:21:56
【问题描述】:
我有一个Request 类型:
data Request =
Request {
reqType :: RequestType,
path :: String,
options :: [(String, String)]
} deriving Show
我正在解析它(来自原始的HTTP 请求),如下所示:
parseRawRequest :: String -> Request
parseRawRequest rawReq =
Request {
reqType = parseRawRequestType rawReq,
path = parseRawRequestPath rawReq,
options = parseRawRequestOps rawReq
}
现在,对parseRawRequestType、parseRawRequestPath(等)的调用可能会失败。为了使我的代码更有弹性,我将它们的类型签名从:
parseRawRequestType :: String -> RequestType
到
parseRawRequestType :: String -> Maybe RequestType
但是将 parseRawRequest 变成 Maybe Request 的最佳方法是什么?我是否必须手动检查 Nothing 的每个组件(reqType、path、options),还是我遗漏了其他方法?
一定有办法以某种方式组合对象创建和Nothing-checking!
我写了以下,但感觉很乱,不理想:(未经测试)
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
干杯。
【问题讨论】:
-
问题标题中的“sum type”一词有点令人困惑,因为您的
Request类型是多个 Maybe 字段的 product,而不是它们的总和。 -
你是 100% 正确的。已编辑。