- Open src/Main.hs.
- Import the Data.Either module:
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:
Division by Zero"
safeDiv (Right i) (Right j) = Right (i `div` j)
- 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)
- Build and execute the project:
stack build
stack exec -- using-either
- You should see the following output:
