[英]Inside Haskell Monads
I have the following code that compiles and runs fine. 我有以下代码可以编译并运行良好。 I tried to make it more compact by replacing case newEmployee of
with case scanEmployee p of
, but it didn't work. 我试图通过用case scanEmployee p of
替换case newEmployee of
来使其更紧凑,但是它不起作用。 There's probably an easy way to remove newEmployee
(and newTeam
) from the code right? 从代码中删除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 ...
You could use LambdaCase
and be explicit with >>=
instead of using do
blocks. 您可以使用LambdaCase
并使用>>=
进行显式表示,而不要使用do
块。 The result is not much shorter: 结果不会短很多:
scanEmployee p >>= \case
Left errorMsg -> return (Left errorMsg)
Right e -> do ...
You can simplify your code a bit with mapM
and sequence
: 您可以使用mapM
和sequence
来简化代码:
mapM scanEmployee :: [Employee] -> State (Int, Int) [Either String Employee')
sequence :: [ Either String a ] -> Either String [ a ]
(Note that these type signatures are simplifications and the actual types are more general. Specifically mapM
and sequence
work for any monad (not just Either String
) and any traversable (not just ([])
)) (请注意,这些类型签名是简化的,实际类型更通用。具体而言, mapM
和sequence
适用于任何monad(不仅是Either String
)和任何可遍历的(不仅是([])
))
And write a simple solution: 并编写一个简单的解决方案:
scanTeam = fmap sequence . mapM scanEmployee
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.