typeclasses / haskell-phrasebook

The Haskell Phrasebook: a quick intro to Haskell via small annotated example programs
https://typeclasses.com/phrasebook
210 stars 22 forks source link

Errors #11

Open chris-martin opened 4 years ago

chris-martin commented 4 years ago

There are a lot of things we could talk about on this topic.

Just as a jumping-off point, here's some code that is more or less a direct translation from Go By Example:

import Data.Foldable (for_)

data Error =
  Error
    { arg :: Int
    , problem :: String
    }
  deriving Show

f arg =
  case arg of
    42 -> Left (Error arg "Can't work with it")
    x  -> Right (x + 3)

t1 =
  do
    x <- f 7
    y <- f 8
    z <- f 9
    return (x, y, z)

t2 =
  do
    x <- f 41
    y <- f 42
    z <- f 43
    return (x, y, z)

main =
  do
    for_ [7, 42] $ \i ->
        case (f i) of
            Left e  -> putStrLn ("f failed: " ++ show e)
            Right r -> putStrLn ("f worked: " ++ show r)

    putStrLn (show t1)

    putStrLn (show t2)
$ runhaskell errors.hs
f worked: 10
f failed: Error {arg = 42, problem = "Can't work with it"}
Right (10,11,12)
Left (Error {arg = 42, problem = "Can't work with it"})

I don't think a demonstrating involving ExceptT Error IO would be out of line either.