Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 功能类似于;什么时候;但是返回一个值?_Haskell_Monads_Applicative_Maybe - Fatal编程技术网

Haskell 功能类似于;什么时候;但是返回一个值?

Haskell 功能类似于;什么时候;但是返回一个值?,haskell,monads,applicative,maybe,Haskell,Monads,Applicative,Maybe,有没有办法写得更简洁?我有很多类似这样的函数。它们每个都有一些布尔条件,然后返回一个值或Nothing rootMiddleware :: Application -> Application rootMiddleware app req respond = fromMaybe next . fmap respond $ serveIndex ["questionnaire"] "../app/answer/answer.html" req <

有没有办法写得更简洁?我有很多类似这样的函数。它们每个都有一些布尔条件,然后返回一个值或
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
rootMiddleware::Application->Application
rootMiddleware应用程序请求响应=
也许下一个。fmap响应$
serveIndex[“调查问卷”]。/app/answer/answer.html”请求
serveIndex[“survey”]。/app/builder/builder.html”请求
重定向[]“/调查/表格”请求
哪里
下一步=应用程序请求响应
serveIndex::[Text]->文件路径->请求->响应
serveIndex前缀fp req=
如果前缀`isPrefixOf`pathInfo请求
然后只需$responseFile status200[(“内容类型”,“文本/html”)]fp Nothing
没有别的了
重定向::[Text]->ByteString->Request->Maybe Response
重定向路径部件url请求=
如果pathParts==pathInfo请求
然后只需$redirecttoURL
没有别的了

非常接近,但它不允许您在应用程序中返回值。这个案子有没有类似的东西

听起来你好像在找
守卫

guard :: Alternative f => Bool -> f ()
guard c = if c then pure () else empty
然后你可以重写

if c then Just x else Nothing
作为


这也适用于
do
表示法。感谢Daniel Wagner的
对我来说已经相当简洁了,如果..你可以使用
bool::bool->a->a
而不是
。。然后。。否则
如果您发现更有吸引力,请不要使用臭名昭著的
fail
。它过去使用的是
mzero
,但自从AMP以来,它被推广使用
备选方案
空的
@rjanJohansen,哎呀!很高兴听到。我更喜欢定义
()::可选f=>Bool->fa->fa;真x=x;False x=空
,因此代替
x
x <$ guard c
guard c *> e
fromMaybe x . fmap f
maybe x f