Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 57 Β· Practice and interviews

Common Mistakes and Error Messages

Learn the Haskell mistakes beginners hit most: type errors, layout problems, ambiguous types, partial functions and space leaks, and how to read GHC messages.

Every Haskell programmer spends their first weeks arguing with the compiler. The good news is that the arguments follow patterns. A handful of mistakes cause most of the red text, and GHC's messages become friendly once you know where to look.

This lesson walks through the mistakes you will meet most often, shows what GHC says about them, and gives the fix. The Haskell blocks are read-only because Haskell does not run on this site. The two runnable examples are JavaScript stand-ins that show the ideas (partial functions and delayed work) and say clearly what is real Haskell and what is not. The exact wording of GHC messages changes between versions, so treat the messages below as typical, not as exact quotes.

How to read a GHC message

A type error has the same skeleton every time:

TEXT
Main.hs:7:22: error: [GHC-83865]
    β€’ Couldn't match expected type β€˜Int’ with actual type β€˜[Char]’
    β€’ In the first argument of β€˜(+)’, namely β€˜"one"’
      In the expression: "one" + 1
      In an equation for β€˜total’: total = "one" + 1

Read it from the top:

  1. Location: file, line and column (7:22). The error is detected here, but the real cause may be earlier.
  2. Expected versus actual: the compiler needed one type and found another. Decide which of the two you meant.
  3. Context lines (In the first argument of ...) trace the path from the failing piece up to the whole definition.
  4. The bracketed code, such as GHC-83865, can be searched in the error index of the GHC documentation.

Two habits help a lot. Fix the first error in the file first, since later ones are often knock-on effects. And give every top-level function a type signature: without one, GHC infers a type from the body, and the error appears far from your real mistake. See type signatures for the basics.

Reading an error

Location File, line, column.
Expected vs actual Which side did you mean?
Context Follow the "In the..." lines upward.

Fix the first error first.

1 / 2

Mixing numeric types

Haskell never converts numbers silently. This fails:

HASKELL
average :: [Int] -> Double
average xs = sum xs / length xs

sum xs is an Int, and / only works on types of the Fractional class, which Int is not. GHC reports something like No instance for (Fractional Int) arising from a use of β€˜/’. The fix is to convert explicitly with fromIntegral:

HASKELL
average :: [Int] -> Double
average xs = fromIntegral (sum xs) / fromIntegral (length xs)

The related error is using / where you wanted whole-number division. Use div and mod for Int and Integer, / for Double. More about the classes involved is in Type Classes.

Forgetting that function application is not a call

Parentheses group; they do not call. These two lines mean very different things:

HASKELL
print (length xs)   -- print applied to (length xs)
print length xs     -- print applied to TWO arguments: error

The second gives a message about print being applied to too many arguments, or about a missing Show instance for a function (No instance for (Show ([a0] -> Int))). The cure is to remember that application is just a space and associates to the left. When a pipeline gets deep, use $ or . instead of stacking parentheses; see lambdas and composition.

A neighbour of this mistake is passing a negative literal without parentheses: abs -5 parses as abs - 5. Write abs (-5).

Layout and indentation errors

Haskell uses indentation to find where blocks start and end. The rule you need most: items in the same block must start in the same column. This is wrong because the second line is indented one space too far:

HASKELL
main :: IO ()
main = do
  putStrLn "first"
   putStrLn "second"

The second line looks like a continuation of the first, so GHC tries to pass putStrLn and "second" as extra arguments. Expect something like Couldn't match expected type β€˜IO t0’ ... with actual type β€˜String -> IO ()’ or a parse error. Check these causes:

  • A tab character mixed with spaces. Configure your editor to insert spaces.
  • A let block inside do where the following bindings are not aligned with the first name.
  • An if inside do with then and else less indented than if (modern GHC accepts this inside do, older code and some contexts do not).
  • A where clause indented less than the function body it belongs to.
HASKELL
-- Aligned: both bindings start in the same column
let a = 1
    b = 2

If GHC reports a parse error (possibly incorrect indentation or mismatched brackets), look at the line it names and the one just above it.

Ambiguous types

Sometimes nothing is wrong but GHC cannot decide which type you mean:

HASKELL
main :: IO ()
main = print (read "42")

read can produce any type that has a Read instance, and print accepts any Showable value, so the type variable has no anchor. GHC reports Ambiguous type variable β€˜a0’ arising from a use of β€˜read’ prevents the constraint β€˜(Read a0)’ from being solved. Annotate the result:

HASKELL
main = print (read "42" :: Int)

Numeric literals do not have this problem for simple cases, because GHC applies defaulting: an unconstrained numeric type becomes Integer (or Double when fractional). Defaulting only happens when every constraint comes from the standard classes, which is why show (2 ^ 10) works but a custom class constraint can make the same expression ambiguous.

Partial functions

A partial function is undefined for some inputs of its declared type. head [], tail [], fromJust Nothing, xs !! 99 on a short list and read "oops" :: Int all crash at run time, and the compiler is happy with every one of them. Incomplete patterns do the same:

HASKELL
describe :: Maybe Int -> String
describe (Just n) = "got " ++ show n
-- no case for Nothing

At run time that yields Non-exhaustive patterns in function describe. Turn on -Wall (or at least -Wincomplete-patterns) and GHC will warn you at compile time. Prefer total alternatives: pattern match, use Maybe, or use readMaybe from Text.Read. The lessons on Maybe and Either and pattern matching cover the patterns in depth.

This stand-in is JavaScript, not Haskell. It models Maybe as tagged objects to show the difference between a crash and a value that says "nothing here":

JS Partial vs total (JS stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In real Haskell the error is a thrown exception of type ErrorCall, not a JavaScript Error. Recent versions of GHC also add a call stack and a warning to head and tail, but the lesson stays the same: avoid them in code that must not crash.

Space leaks from laziness

Laziness can quietly keep a long chain of unfinished work in memory. The classic example is a lazy accumulator:

HASKELL
count :: [a] -> Int
count = foldl (\n _ -> n + 1) 0

Until the final result is demanded, n + 1 stays a thunk that refers to the previous thunk. The fix is a strict fold from Data.List:

HASKELL
import Data.List (foldl')

count :: [a] -> Int
count = foldl' (\n _ -> n + 1) 0

Other leak sources are lazy fields in long-lived records, modifyIORef (use modifyIORef') and lazy state in a Data.Map (use Data.Map.Strict). The full story is in strictness and bang patterns. Because the program is correct but slow, the symptom is rising memory in a profile, not an error message.

JS A chain of pending work (JS stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This only mimics the idea. GHC's thunks are heap objects managed by its runtime, and its optimizer often removes the chain for simple folds when you compile with -O.

More errors you will meet

  • Missing instance: No instance for (Show Shape) means you printed a type that has no Show. Add deriving Show.
  • Missing constraint: No instance for (Ord a) in a polymorphic function means the signature must say Ord a =>.
  • Rigid type variable: Couldn't match type β€˜a’ with β€˜Int’ ... β€˜a’ is a rigid type variable means your signature promised any type but the body uses a specific one.
  • Not in scope: a typo, a missing import, or a name defined in a later let. Qualified names need the prefix: Map.lookup, not lookup.
  • Shadowing in where: reusing xs for a new meaning hides the outer one. -Wall warns about it.
  • if without else: every if is an expression and needs both branches.
  • String versus Text: with OverloadedStrings off, "hi" is a String. Convert with T.pack and T.unpack.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. A GHC type error says 'Couldn't match expected type Int with actual type [Char]'. What does it mean?

    Expected is what the context requires and actual is what the expression has. You decide which of the two you meant.
  2. 2. Why does print (read "42") fail to compile?

    Nothing fixes the type, so an annotation such as :: Int is needed.
  3. 3. Which of these is a partial function?

    head has no answer for the empty list and throws an exception at run time, while the others are defined for every value of their input type.
  4. 4. What is the usual fix for a space leak caused by foldl?

    foldl' evaluates the accumulator each step, so no long chain of thunks is built.

Summary

  • Read GHC messages by location, expected versus actual type, and context; fix the first error first.
  • Convert numbers explicitly with fromIntegral, and use div for integers and / for fractional types.
  • Keep items of a block in the same column and avoid tabs.
  • Annotate results of read and other polymorphic values to resolve ambiguity.
  • Turn on -Wall, and prefer total functions and Maybe over head, fromJust and incomplete patterns.
  • Use foldl', strict fields and strict maps to avoid space leaks.

Next: Haskell Interview Questions.