O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required