简体   繁体   English

haskell中大小写匹配的替代功能

[英]Alternative function for case match in haskell

I am writing an API in Haskell which involves a DB query.我正在用 Haskell 编写一个涉及数据库查询的 API。 Function will be something like do a db query and then return the response back.函数类似于执行数据库查询,然后返回响应。

doAPICall :: Request -> (Monad m Response)
doAPICall req = do
    maybeValDB <- getValFromDB (req.tokenId) -- Returns maybe type
    -- My current logic was to do a case match of maybe
    case maybeValDB of
        Just val -> do
            --Some logic here using that val and return the response
            pure response
        Nothing -> pure response

I am currently getting a maybe type from the DB query function.我目前正在从 DB 查询函数中获取可能的类型。 Is there a simple way like a one liner code to avoid this case match and send the response back.有没有像单行代码这样的简单方法来避免这种情况匹配并将响应发回。

I thought of using fromMaybe but it should have same type for the default value.我想过使用fromMaybe但它的默认值应该具有相同的类型。 Here in this case if db returns Nothing I just want to exit the function with some response.在这种情况下,如果 db 返回 Nothing 我只想退出函数并做出一些响应。

In general in many cases the response which I get will be of maybe type and I have to do case matches the code looks very ugly and have repetitive patterns.一般来说,在许多情况下,我得到的响应可能是类型,我必须进行大小写匹配,代码看起来非常难看并且有重复的模式。 Can anyone tell me better alternative for this instead of having case matches everywhere.谁能告诉我更好的选择,而不是到处都有大小写匹配。

Perhaps what you're looking for is maybe ?也许您正在寻找的是maybe

doAPICall :: Request -> (Monad m Response)
doAPICall req = do
    maybeValDB <- getValFromDB (req.tokenId)
    flip (maybe $ pure response) maybeValDB $ \val -> do
      -- Some logic here using that val and return the response
      pure response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM