我正在用 Haskell 撰寫一個涉及資料庫查詢的 API。函式類似于執行資料庫查詢,然后回傳回應。
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
我目前正在從 DB 查詢函式中獲取可能的型別。有沒有像單行代碼這樣的簡單方法來避免這種情況匹配并將回應發回。
我想過使用fromMaybe,但默認值應該具有相同的型別。在這種情況下,如果 db 回傳 Nothing 我只想退出函式并做出一些回應。
一般來說,在許多情況下,我得到的回應可能是型別,我必須進行大小寫匹配,代碼看起來非常難看并且有重復的模式。誰能告訴我更好的選擇,而不是到處都有大小寫匹配。
uj5u.com熱心網友回復:
也許您正在尋找的是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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474020.html
