有没有办法更简洁地写这个?我有很多看起来像这样的功能。它们中的每一个都有一些布尔条件,然后返回一个值或Nothing
rootMiddleware :: Application -> Application
rootMiddleware app req respond =
fromMaybe next . fmap respond $
serveIndex ["questionnaire"] "../app/answer/answer.html" req
<|> serveIndex ["survey"] "../app/builder/builder.html" req
<|> redirect [] "/survey/forms" req
where
next = app req respond
serveIndex :: [Text] -> FilePath -> Request -> Maybe Response
serveIndex prefix fp req =
if prefix `isPrefixOf` pathInfo req
then Just $ responseFile status200 [("Content-Type", "text/html")] fp Nothing
else Nothing
redirect :: [Text] -> ByteString -> Request -> Maybe Response
redirect pathParts url req =
if pathParts == pathInfo req
then Just $ redirectTo url
else Nothing
when
非常接近,但它不允许您在应用中返回值。这种情况有同等的东西吗?
答案 0 :(得分:9)
听起来你正在寻找guard
:
guard :: Alternative f => Bool -> f ()
guard c = if c then pure () else empty
然后你可以重写
if c then Just x else Nothing
作为
x <$ guard c
如果您不直接Just
,请考虑
guard c *> e
也适用于do
表示法。感谢Daniel Wagner的<$
表达。
另请注意
fromMaybe x . fmap f
写得更好
maybe x f