我有一个像这样的功能:
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
只有一个子句的语句看起来很奇怪……我如何有条件地执行“操作”?
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
wasLeft
或Right
要么,都需要生成type的值,方法是在the之后返回一个公共值,case
或者baz
从两个大小写分支都返回一个值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句