What are the difference in usage between Either and Except in Haskell?

淺唱寂寞╮ 提交于 2019-12-04 07:59:38

As noted in the comments, it's easy to convert between Except & Either. The runtime representation is the same, even.

I would always choose to use Either. It's ubiquitous in libraries. I very rarely see Except.

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.

The difference is in the instance of Alternative. The "base" package does not export any for Either, as I guess because the authors didn't want to introduce a bias towards any of the values, which on itself is because Either is supposed to be a general sum-type, not just for representing possible errors. However the "transformers" package does provide an orphan instance, which binds it to the Error class:

Error e => Alternative (Either e)

However the community never accepted neither that typeclass or the orphan instance, which is why it is now deprecated. IOW you can look at this as if Either still has no instance of Alternative.

The Except type does have a non-orphan instance, which doesn't even bind the user to any made-up classes, but Monoid instead:

(Functor m, Monad m, Monoid e) => Alternative (ExceptT e m)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!