Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

either

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?

like image 745
fredoverflow Avatar asked Aug 27 '11 08:08

fredoverflow


2 Answers

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.

like image 104
pyrospade Avatar answered Sep 18 '22 14:09

pyrospade


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.

like image 30
hammar Avatar answered Sep 16 '22 14:09

hammar