开发者

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

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) (co开发者_运维知识库nst True)

Is there something like that in the standard library?


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.


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.


No, but you can write:

import Data.Either

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


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...


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜