7

我有以下 Web API 的小型小型示例应用程序,该应用程序需要一个巨大的 JSON 文档,并且应该将其解析为片段并报告每个片段的错误消息。

以下代码是使用 EitherT(和 errors 包)的工作示例。然而,问题是 EitherT 中断了第一个 Left 遇到的计算,只返回它看到的第一个“错误”。我想要的是一个错误消息列表,所有这些都是可能产生的。例如,如果第一行runEitherT失败,那么就没有什么可以做的了。但是如果第二行失败,那么我们仍然可以尝试运行后续行,因为它们对第二行没有数据依赖。因此,理论上我们可以一次性产生更多(不一定是全部)错误消息。

是否可以懒惰地运行所有计算并返回我们能找到的所有错误消息?

{-# LANGUAGE OverloadedStrings #-}

module Main where

import Data.ByteString.Lazy.Char8 (pack)
import Web.Scotty as S
import Network.Wai.Middleware.RequestLogger
import Data.Aeson
import Data.Aeson.Types
import Control.Lens hiding ((.=), (??))
import Data.Aeson.Lens
import qualified Data.Text as T
import Control.Error
import Control.Applicative
import qualified Data.HashMap.Strict as H
import Network.HTTP.Types

data TypeOne = TypeOne T.Text TypeTwo TypeThree
  deriving (Show)

data TypeTwo = TypeTwo Double
  deriving (Show)

data TypeThree = TypeThree Double
  deriving (Show)

main :: IO ()
main = scotty 3000 $ do
  middleware logStdoutDev

  post "/pdor" $ do
    api_key <- param "api_key"
    input   <- param "input"

    typeOne <- runEitherT $ do
      result       <- (decode (pack input) :: Maybe Value) ?? "Could not parse. Input JSON document is malformed"
      typeTwoObj   <- (result ^? key "typeTwo")            ?? "Could not find key typeTwo in JSON document."
      typeThreeObj <- (result ^? key "typeThree")          ?? "Could not find key typeThree in JSON document."
      name         <- (result ^? key "name" . _String)     ?? "Could not find key name in JSON document."
      typeTwo      <- hoistEither $ prependLeft "Error when parsing TypeTwo: " $ parseEither jsonTypeTwo typeTwoObj
      typeThree    <- hoistEither $ prependLeft "Error when parsing TypeThree: " $ parseEither jsonTypeThree typeThreeObj

      return $ TypeOne name typeTwo typeThree

    case typeOne of
      Left errorMsg -> do
        _ <- status badRequest400
        S.json $ object ["error" .= errorMsg]
      Right _ ->
        -- do something with the parsed Haskell type
        S.json $ object ["api_key" .= (api_key :: String), "message" .= ("success" :: String)]

prependLeft :: String -> Either String a -> Either String a
prependLeft msg (Left s) = Left (msg ++ s)
prependLeft _ x = x

jsonTypeTwo :: Value -> Parser TypeTwo
jsonTypeTwo (Object v) = TypeTwo <$> v .: "val"
jsonTypeTwo _ = fail $ "no data present for TypeTwo"

jsonTypeThree :: Value -> Parser TypeThree
jsonTypeThree (Object v) = TypeThree <$> v .: "val"
jsonTypeThree _ = fail $ "no data present for TypeThree"

如果有人有一些重构建议,也可以接受。

4

2 回答 2

9

正如我在评论中提到的,您至少有两种累积错误的方法。下面我详细说明这些。我们需要这些导入:

import Control.Applicative
import Data.Monoid
import Data.These

TheseT单子变压器

免责声明:packageTheseT中调用。ChronicleTthese

看一下These数据类型的定义:

data These a b = This a | That b | These a b

这里ThisThat对应数据类型的Left和。例如,数据构造函数能够实现累积能力:它包含结果(类型)和先前错误的集合(类型的集合)。RightEitherTheseMonadba

利用已经存在的These数据类型定义,我们可以轻松地创建类似ErrorTmonad 的转换器:

newtype TheseT e m a = TheseT {
  runTheseT :: m (These e a)
}

TheseTMonad以下方式的一个实例:

instance Functor m => Functor (TheseT e m) where
  fmap f (TheseT m) = TheseT (fmap (fmap f) m)

instance (Monoid e, Applicative m) => Applicative (TheseT e m) where
  pure x = TheseT (pure (pure x))
  TheseT f <*> TheseT x = TheseT (liftA2 (<*>) f x)

instance (Monoid e, Monad m) => Monad (TheseT e m) where
  return x = TheseT (return (return x))
  m >>= f = TheseT $ do
    t <- runTheseT m
    case t of
      This  e   -> return (This e)
      That    x -> runTheseT (f x)
      These _ x -> do
        t' <- runTheseT (f x)
        return (t >> t')  -- this is where errors get concatenated

Applicative积累ErrorT

免责声明:m (Either e a)由于您已经在newtype 包装器中工作,因此这种方法更容易适应,但它仅适用于Applicative设置。

如果实际代码只使用Applicative接口,我们可以ErrorT改变它的Applicative实例。

让我们从非变压器版本开始:

data Accum e a = ALeft e | ARight a

instance Functor (Accum e) where
  fmap f (ARight x) = ARight (f x)
  fmap _ (ALeft e)  = ALeft e

instance Monoid e => Applicative (Accum e) where
  pure = ARight
  ARight f <*> ARight x = ARight (f x)
  ALeft e  <*> ALeft e' = ALeft (e <> e')
  ALeft e  <*> _        = ALeft e
  _        <*> ALeft e  = ALeft e

请注意,在定义时,<*>我们知道双方是否都是ALefts 并因此可以执行<>。如果我们尝试定义相应的Monad实例,我们会失败:

instance Monoid e => Monad (Accum e) where
  return = ARight
  ALeft e >>= f = -- we can't apply f

所以Monad我们可能拥有的唯一实例是Either. 但是ap不一样<*>

Left a <*>  Left b  ≡  Left (a <> b)
Left a `ap` Left b  ≡  Left a

所以我们只能使用Accumas Applicative

现在我们可以Applicative基于以下定义变压器Accum

newtype AccErrorT e m a = AccErrorT {
  runAccErrorT :: m (Accum e a)
}

instance (Functor m) => Functor (AccErrorT e m) where
  fmap f (AccErrorT m) = AccErrorT (fmap (fmap f) m)

instance (Monoid e, Applicative m) => Applicative (AccErrorT e m) where
  pure x = AccErrorT (pure (pure x))
  AccErrorT f <*> AccErrorT x = AccErrorT (liftA2 (<*>) f x)

请注意,AccErrorT e m本质上是Compose m (Accum e).


编辑:

AccError被称为AccValidation内。validation

于 2014-05-12T13:59:35.330 回答
0

我们实际上可以将其编码为箭头(Kleisli 变换器)。

newtype EitherAT x m a b = EitherAT { runEitherAT :: a -> m (Either x b) }

instance Monad m => Category EitherAT x m where
  id = EitherAT $ return . Right
  EitherAT a . EitherAT b
       = EitherAT $ \x -> do
              ax <- a x
              case ax of Right y -> b y
                         Left e  -> return $ Left e

instance (Monad m, Semigroup x) => Arrow EitherAT x m where
  arr f = EitherAT $ return . Right . f
  EitherAT a *** EitherAT b = EitherAT $ \(x,y) -> do
      ax <- a x
      by <- b y
      return $ case (ax,by) of
        (Right x',Right y') -> Right (x',y')
        (Left e  , Left f ) -> Left $ e <> f
        (Left e  , _      ) -> Left e
        (  _     , Left f ) ->        Left f
  first = (***id)

只是,这会违反箭头定律(你不能a *** bfirst a >>> second b不丢失a错误信息的情况下重写)。但是,如果您基本上将所有Lefts 视为调试设备,您可能会认为这没关系。

于 2014-05-12T12:26:19.003 回答