我有这样的功能:
myFnc :: foo -> StateT bar IO baz -- foo, bar, and baz are complex
-- data structures
myFnc x =
do result <- anotherFnc x -- anotherFnc :: foo -> StateT bar IO baz
-- result is of type Either (= baz), now I need to perform
-- an action only if result is created with data costructor 'Right'
return result
我只能想到case
:
case result of
Right val -> ...
但只有一个条款的case
语句看起来很奇怪......我如何有条件地执行'动作'?
答案 0 :(得分:4)
case
是正确的方法,但你需要处理所有情况。
case result of
Right val -> ... -- do some actions with val
Left _ -> return () -- do nothing
较短的替代方法是从for_
Data.Foldable
for_ result $ \val -> ... -- do something with val
但是,您的问题并不清楚您要从myFnc
返回什么。您的签名的类型为foo -> StateT bar IO baz
,但无论baz
是result
还是Left
,您都需要生成Right
类型的值case
之后的公共值或从两个案例分支返回baz
值。
答案 1 :(得分:3)
您可以使用类型为when
的库函数Monad m => Bool -> m () -> m ()
。如果您还有一个检查构造函数的函数isRight
,那么您可以执行以下操作:
do result <- anotherFnc x --
when (isRight result) ...