Errors in Haskell
In Haskell, error handling is typically done using the Either
type or custom error types. We’ll demonstrate both approaches in this example.
In this Haskell version:
We define
f
to returnEither String Int
. This is similar to returning(int, error)
in Go, but uses Haskell’sEither
type.For the tea-making example, we define a custom
TeaError
type with two constructors:OutOfTea
andNoPower
. This is similar to using sentinel errors in Go.The
makeTea
function returnsEither TeaError ()
. The()
(unit type) is used when we only care about whether an error occurred, not about returning a value.In the
main
function, we use pattern matching withcase
expressions to handle errors. This is similar to checking fornil
errors in Go.We use
forM_
(a variant offor
that discards its result) to iterate over lists, similar to thefor
loops in the Go example.Error checking in Haskell is explicit through the use of
Either
, similar to Go’s approach of returning errors as values.
To run this program, save it as Errors.hs
and use:
This Haskell code demonstrates error handling techniques that are idiomatic to Haskell while maintaining the spirit of explicit error handling from the original example.