在 Haskell 个 Monad 中

Inside Haskell Monads

我有以下代码可以正常编译和运行。我试图通过用 case scanEmployee p of 替换 case newEmployee of 来使其更紧凑,但它没有用。可能有一种简单的方法可以从代码中删除 newEmployee(和 newTeam),对吗?

module Main( main ) where
import Control.Monad.State

data Employee  = EmployeeSW  Int Int | EmployeeHW Int String deriving ( Show )
data Employee' = EmployeeSW'     Int | EmployeeHW'    String deriving ( Show )

scanTeam :: [Employee] -> State (Int,Int) (Either String [Employee'])
scanTeam [    ] = return (Right [])
scanTeam (p:ps) = do
    newEmployee <- scanEmployee p
    case newEmployee of
        Left errorMsg -> return (Left errorMsg)
        Right e -> do
            newTeam <- scanTeam ps
            case newTeam of
                Right n -> return (Right (e:n))
                Left errorMsg -> return (Left errorMsg)

scanEmployee :: Employee -> State (Int,Int) (Either String Employee')
-- actual code for scanEmployee omitted ...

您可以使用 LambdaCase 并明确使用 >>= 而不是使用 do 块。结果也短不了多少:

scanEmployee p >>= \case
    Left errorMsg -> return (Left errorMsg)
    Right e       -> do ...

您可以使用 mapMsequence 稍微简化您的代码:

mapM scanEmployee :: [Employee] -> State (Int, Int) [Either String Employee')

sequence :: [ Either String a ] -> Either String [ a ]

(请注意,这些类型签名是简化的,实际类型更通用。具体来说,mapMsequence 适用于任何 monad(不仅仅是 Either String)和任何可遍历的 (不只是 ([])))

并写一个简单的解决方案:

scanTeam = fmap sequence . mapM scanEmployee