Haskell中的Either和Except在用法上有什么区别? [英] What are the difference in usage between Either and Except in Haskell?
问题描述
我有一个可以从Haskell中的多个参数创建的类,该类需要对这些参数进行一些复杂的验证。当前我有类似的东西
I have a class that can be created from several arguments in Haskell which requires some complex validation of those arguments. Currently I have something like
makeAThingExcept :: String -> String -> ... String -> Except ThingError AThing
makeAThingExcept s1 s2 ... = do
unless (s1CheckPasses s1) (throwError (BadS1 s1))
...
data ThingError = BadS1 String ...
instance Show ThingError where
show (BadS1 s) = "Bad S1: " ++ s
makeAThing :: String -> String -> ... String -> AThing
makeAThing s1 s2 ... = case runExcept (makeAThingExcept s1 s2 ...) of
Right thing -> thing
Left err -> error (show err)
通过使用更具体的类型,是否还有更好的方法比 String
作为 makeAThingExcept
的参数,是否有理由更喜欢 Except
在以上
的情况下? 除
与两者 c之外的功能和习语之间有什么区别?
Setting aside whether there is a better way to do this by using more specific types than String
as arguments to makeAThingExcept
, is there a reason to prefer Except
over Either
in a case like this? What are the differences here between the capabilities and idiom of Except
vs Either
?
推荐答案
如注释中所述,很容易在除
与& 要么
。即使在运行时表示形式也是一样。
As noted in the comments, it's easy to convert between Except
& Either
. The runtime representation is the same, even.
我总是选择使用 Ething
。它在图书馆中无处不在。我很少看到例外
。
I would always choose to use Either
. It's ubiquitous in libraries. I very rarely see Except
.
除了
是一个 ExceptT的特例,您将在库中看到 。如果您发现自己使用 Reader SomeType(任意一个)
或 IO(任意一个)
或 Monad m => m(或者e a)
,那么您可能需要考虑 ExceptT
。最好不要担心,直到
都容易使用,直到不再使用。
Except
is a special case of ExceptT, which you will see in libraries. If you find yourself writing a lot of functions with Reader SomeType (Either e a)
or IO (Either e a)
or Monad m => m (Either e a)
, then you might want to consider ExceptT
. It's fine not to worry about it until then - Either
is easier to use until it isn't.
这篇关于Haskell中的Either和Except在用法上有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!