Haskell 有条件地执行';行动';在do块中

Haskell 有条件地执行';行动';在do块中,haskell,conditional-statements,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 Eith

我有这样一个函数:

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
do result <- anotherFnc x --
   when (isRight result) ...

但是只有一个子句的
case
语句看起来很奇怪。。。如何有条件地执行“操作”?

案例是正确的方法,但您需要处理所有案例

case result of
     Right val -> ... -- do some actions with val
     Left _    -> return () -- do nothing
一个较短的替代方案是从


但是,您的问题不清楚您想从
myFnc
返回什么。您的签名的类型为
foo->StateT bar IO baz
,但是您需要生成
baz
类型的值,而不管
结果是
还是
,方法是在
案例之后返回一个公共值,或者从这两个案例返回一个
baz
值案例分支

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

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
do result <- anotherFnc x --
   when (isRight result) ...

做得很好有而且-但你这里并不是只有一个案例-仍然有
剩余的
-我想如果你添加案例,你的程序更可读,所有人都可以看到你只是想忽略它。@CarstenKönig,嗯。。你可能是对的。我将在
的时候查看
,不管怎样。顺便说一句:我假设这都在
IO
单子中?您应该添加这些类型签名;)@马克:你不能用
return()
来处理
左边的
案例吗?(另外,如果您在
右侧
案例中显示您正在执行的操作,则会有所帮助。)@Mark:如果您至少指明了类型,则会有所帮助!
return()
仅在另一个案例的类型为
m()
时有效。
isRight
是标准函数吗?胡格尔找不到它。我应该自己写吗?@Mark:
数据。要么
isRight
,请参见: