I am writing an API in Haskell which involves a DB query. 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. 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. Here in this case if db returns Nothing I just want to exit the function with some response.
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.
CodePudding user response:
Perhaps what you're looking for is 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