🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Error Accumulation

Haskell error accumulation is the practice of collecting every validation problem instead of stopping at the first one. It uses a list of messages where Either would stop early.

Either stops at the first Left

Both checks would fail. The chain reports only the name problem.

checkName :: String -> Either String String
checkName n = if null n then Left "name empty" else Right n
checkAge :: Int -> Either String Int
checkAge a = if a < 0 then Left "age negative" else Right a
main :: IO ()
main = do
  print (checkName "" >>= (\_ -> checkAge (-1)))

A list collects every problem

Both checks fail here. The list holds both messages.

collect :: String -> Int -> [String]
collect n a = ["name empty" | null n] ++ ["age negative" | a < 0]
main :: IO ()
main = do
  print (collect "" (-1))

Both shapes side by side

The Either result shows one problem. The list result shows both problems.

checkName :: String -> Either String String
checkName n = if null n then Left "name empty" else Right n
checkAge :: Int -> Either String Int
checkAge a = if a < 0 then Left "age negative" else Right a
collect :: String -> Int -> [String]
collect n a = ["name empty" | null n] ++ ["age negative" | a < 0]
main :: IO ()
main = do
  print (checkName "" >>= (\_ -> checkAge (-1)), collect "" (-1))

Example

validateAll :: String -> Int -> String -> [String]
validateAll n a e = ["name empty" | null n] ++ ["age negative" | a < 0] ++ ["email bad" | not ('@' `elem` e)]
main :: IO ()
main = do
  print (validateAll "" (-1) "plain", validateAll "Ana" 30 "ana@mail")

Key points

  • Short circuit: an Either chain stops at the first Left and never runs later checks.
  • List: a list of messages can hold one entry for every failed check.
  • Collect: a validation that builds a list returns every problem at once.
  • Empty means good: an empty error list means every check passed.
  • Choose by need: Either fits a single failure, while a list fits a full report.

In this example, the program validates a name, an age, and an email address together. A bad record collects all three problems. A good record collects no problems at all.

Note

the list shape is built by hand, since Either itself cannot hold more than one Left.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Why does an Either chain report only one validation problem?