Can I ask an Either whether it is Left (or Right)?

限于喜欢 提交于 2019-12-01 00:30:45

问题


I know I can usually just pattern match, but sometimes I would find these functions useful:

isLeft  = either (const True) (const False)
isRight = either (const False) (const True)

Is there something like that in the standard library?


回答1:


While this is pretty old, posting here for reference.

This is now in the standard library under Data.Either since 4.7:

https://hackage.haskell.org/package/base-4.7.0.0/docs/Data-Either.html

isLeft :: Either a b -> Bool

Return True if the given value is a Left-value, False otherwise.

isRight :: Either a b -> Bool

Return True if the given value is a Right-value, False otherwise.




回答2:


As people have been pointing out, there is no such function in the standard library, and you can implement your own in various ways.

However, note that questions of the form "Is X in the standard library?" are most easily answered by Hoogle, since even if you don't know the name of a function, you can search for it by its type.

Hoogle is also smart enough to know that the argument order does not matter, and it will also show results whose types are similar (e.g. more generic) than the type you searched for.

In this case, searching for Either a b -> Bool does not yield any promising matches, so that's a good indicator that it does not exist in the standard library.




回答3:


No, but you can write:

import Data.Either

isLeft = null . rights . return
isRight = null . lefts . return



回答4:


No, there isn't, afaik.

But you can define these functions even easier*:

isLeft (Left _) = True
isLeft _        = False

the same goes for isRight, of course.

EDIT: * Okay, I guess it's arguable if that's easier or not, since it requires more lines of code...




回答5:


As far as I know, there's nothing like this in the standard library. You can define it yourself easily, however.

either l _ (Left  a) = l a
either _ r (Right b) = r b

isLeft (Left _) = True
isLeft _        = False

isRight (Right _) = True
isRight _         = False


来源:https://stackoverflow.com/questions/7213395/can-i-ask-an-either-whether-it-is-left-or-right

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