有条件地在do块中执行'action'

时间:2014-10-13 05:41:58

标签: haskell conditional-statements

我有这样的功能:

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语句看起来很奇怪......我如何有条件地执行'动作'?

2 个答案:

答案 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,但无论bazresult还是Left,您都需要生成Right类型的值case之后的公共值或从两个案例分支返回baz值。

答案 1 :(得分:3)

您可以使用类型为when的库函数Monad m => Bool -> m () -> m ()。如果您还有一个检查构造函数的函数isRight,那么您可以执行以下操作:

do result <- anotherFnc x --
   when (isRight result) ...