Using Either
Similar to Maybe, another data type that is used often in Haskell is Either. While Maybe decides to map something or nothing, Either goes with two types and keeps either of them. In this recipe, we will construct a safe division using the Either data type and will see how we can represent the error messages in a better way.
Getting ready
Use the following command to create a new project called using-either using the simple template:
stack new using-either simple
Change into the newly created project directory.
How to do it...
- Open
src/Main.hs. - Import the
Data.Eithermodule:
import Data.Either
- Define safe division, handling the division by zero case:
safeDiv :: Either String Int -> Either String Int -> Either
String Int
safeDiv (Left e) _ = Left e -- Any Left _ is an error, we
produce the same
safeDiv _ (Left e) = Left e -- error as a result.
safeDiv (Right i) (Right j) | j == 0 = Left "Illegal Operation:
...