功能类似于 "when" 但 returns 是一个值?

Function like "when" but returns a value?

有没有办法写得更简洁些?我有很多看起来像这样的功能。他们每个人都有一些布尔条件,然后 return 一个值或 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 非常接近,但它不会让您 return 应用程序中的值。这种情况有什么等同的东西吗?

听起来你在找 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