Skip to content

Errors #11

@chris-martin

Description

@chris-martin

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    good for new contributorsPull requests welcome!new exampleThis issue is about writing a new example program.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions