How to do it...

  1. Open src/Main.hs
  2. Import the Data.Either module:
        import Data.Either
  1. 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:
Division by Zero"
safeDiv (Right i) (Right j) = Right (i `div` j)
  1. Use safe division in the main function to illustrate usage of Either:
        main :: IO ()
main = do
let i = Right 10 :: Either String Int
j = Right 2 :: Either String Int
z = Right 0 :: Either String Int

putStrLn $ "Safe division : 10 / 2 = " ++ (show $ safeDiv i j)
putStrLn $ "Safe division : 10 / 0 = " ++ (show $ safeDiv i z)
  1. Build and execute the project:
      stack build
stack exec -- using-either
  1. You should see the following output: