簡體   English   中英

為Either和Maybe單子符號

[英]do notation for Either and Maybe monads

有一種方法:

import Control.Applicative ((<$>))
import Network.HTTP.Types

getJSON :: String -> IO (Either String Value)
getJSON url = eitherDecode <$> simpleHttp url

而不是這樣:

method1 :: String -> IO Object
method1 url = do
                maybeJson <- getJSON url
                case maybeJson of
                   jsonValue -> 
                    case jsonValue of
                      Object jsonObject -> return jsonObject
                      _ -> error "error123"
                  Left errorMsg -> error $ "error456"

我可以做這個:

method1 :: String -> IO Object
method1 url = do
                Right jsonValue <- getJSON url
                case jsonValue of
                  Object jsonObject -> return jsonObject
                  _ -> error "error123"

有沒有辦法在不使用像lens這樣的庫的情況下進一步簡化它?

如果您不關心特定的錯誤消息,則可以進一步合並模式:

method1 url = do
                Right (Object jsonObject) <- getJSON url
                return jsonObject

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM