繁体   English   中英

内部Haskell Monads

[英]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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM