Haskell World logo Haskell WorldWrite code, build worlds
Programming

Haskell Pattern Matching and Guards Explained Clearly

You wrote a function with five equations, GHC compiled it without complaint, and a week later a user hit the one input you never covered and the program died with "Non-exhaustive patterns in function".

A developer's monitor showing a Haskell function with several equations next to a notebook of hand-drawn data type diagrams

You wrote a function with five equations, GHC compiled it without complaint, and a week later a user hit the one input you never covered and the program died with "Non-exhaustive patterns in function". Haskell pattern matching is one of the first features people learn and one of the last they use well. This guide walks through how matching actually works, where guards fit, and the habits that stop partial functions from reaching production.

How Haskell pattern matching actually works

A pattern is a shape that a value either fits or does not. When you define a function with several equations, GHC tries them from top to bottom and picks the first one whose patterns fit the arguments. Matching also binds names: in an equation for a list that starts with the pattern x followed by a cons and xs, the head of the list becomes x and the rest becomes xs for the body of that equation.

There are only a handful of pattern forms to learn:

  • Variables such as x or acc, which match anything and give it a name.
  • The wildcard, written as an underscore, which matches anything and binds nothing.
  • Literals such as 0, 'a' or "GET", which match by equality.
  • Constructors such as Just n, Nothing, Left err or a tuple, which match a specific data constructor and then match its fields with nested patterns.
  • As patterns, written name@pattern, which keep a name for the whole value while also taking it apart.

Order matters more than most beginners expect. If you put a catch-all variable equation first, every later equation is dead code. GHC will warn you about that with -Woverlapping-patterns, which is on by default, but only if you read the warnings.

Matching is also evaluation

Because Haskell is lazy, a pattern is the thing that forces a value. Matching against Just n forces the argument far enough to see which constructor it is, and no further. A plain variable pattern forces nothing. This is why a function that matches on a tuple in its first argument can blow up on undefined while one that uses a variable cannot. If laziness still feels slippery, our piece on why lazy evaluation in Haskell actually matters covers the evaluation model this section relies on.

Guards, case expressions and where they fit

Patterns answer the question "what shape is this value". Guards answer "what is true about it". A guard is a boolean expression after a vertical bar, checked in order, and the first one that evaluates to True wins. A function that classifies an HTTP status code is a typical case: one guard for codes below 300, one for codes below 400, one for codes below 500, and otherwise for the rest.

Case expressions do the same job as multiple equations but inside an expression. They are useful when you only need to match on one intermediate result, such as the return value of a lookup in a Map, without inventing a helper function. A rough rule that works on real codebases:

  1. Use separate equations when the function's behaviour is defined by the shape of its arguments.
  2. Use guards when the shape is the same and the decision depends on a comparison or predicate.
  3. Use a case expression when the value you need to inspect is computed halfway through the function.
  4. Use pattern guards, written with a left arrow inside the guard, when you need to match on the result of a computation and fall through to the next guard if it fails.

Exhaustiveness and the warnings you should turn on

A function that does not cover every possible input is called partial. The Prelude ships several famous ones, including head, tail and fromJust, and each has caused real outages. Your own code becomes partial the moment you forget a constructor.

The fix costs one line in your cabal file. Add -Wall to ghc-options, and if your team agrees, add -Werror=incomplete-patterns so missing cases fail the build instead of producing a warning nobody reads. Since GHC 9.2, -Wincomplete-uni-patterns and -Wincomplete-record-updates are included in -Wall, which catches partial lambdas and let bindings as well.

The payoff shows up when you add a constructor to a type. Suppose a PaymentStatus type has Pending, Settled and Failed, and next quarter you add Refunded. With incomplete pattern warnings promoted to errors, the compiler lists every function in the codebase that now needs a decision about refunds. On one service I worked on, that list had 23 entries, and three of them were in billing code nobody remembered existed.

This pairs naturally with richer types. Replacing a null-like sentinel with a sum type, as described in how the Maybe type replaces null in Haskell, only pays off if the compiler forces you to handle every constructor.

Why the catch-all wildcard is often the wrong default

A lot of style guides and tutorials tell you to finish every function with a wildcard equation "to be safe". I disagree for most domain types, and the reason is the scenario above.

A wildcard silences the exhaustiveness checker permanently. When Refunded is added, a function that ended with an underscore equation keeps compiling and quietly treats refunds the same as whatever the wildcard returned. Maybe that is correct. Usually nobody checked. The safety the wildcard seemed to offer was really a decision made in advance for constructors that did not exist yet.

My rule is simple: for types your team owns and expects to grow, list every constructor explicitly, even when three of them share a result. For types with a huge or open set of values, such as Int, Char, Text or a third-party type you do not control, a final catch-all is reasonable and often necessary. The test is whether a new case appearing later should force someone to think. If yes, no wildcard.

Patterns that make code easier to read

Beyond correctness, a few pattern habits make a module noticeably easier to review:

  • Match on records by field with NamedFieldPuns or RecordWildCards sparingly. Puns are fine. Wildcards hide where names come from, which hurts in a 400-line module.
  • Use view patterns for repeated projections. If five equations all start by calling the same normalising function on an argument, a view pattern moves that call into the pattern itself.
  • Prefer bang patterns over seq for strict accumulators. A bang on the accumulator argument of a loop is clearer and avoids the space leaks that come from a growing chain of thunks.
  • Keep irrefutable patterns, written with a tilde, for the rare case you actually need them. They delay matching until a name is used and turn a clear crash at the call site into a confusing one somewhere later.

Frequently asked questions

What is the difference between pattern matching and guards in Haskell?

Pattern matching checks the structure of a value, such as which constructor it was built with, and binds its parts to names. Guards check boolean conditions on values that have already been matched. Most real functions use both: patterns to take a value apart and guards to decide what to do with the pieces.

How do I fix "Non-exhaustive patterns in function" in Haskell?

The error means the function received a value that none of its equations cover. Compile with -Wall to see exactly which constructors or literals are missing, then add equations for them. If the missing case is genuinely impossible, encode that in the types rather than leaving the function partial.

Does pattern matching order matter in Haskell?

Yes. GHC tries equations and case alternatives from top to bottom and uses the first one that matches. A general pattern placed above a specific one will shadow it, and GHC reports this with an overlapping patterns warning.

AS
Adil Sato

Adil Sato teaches programming concepts at a community college and writes online guides for the questions students ask most in the second week of class, not the first. His focus is on making type systems, monads, and functional patterns understandable without reducing them to metaphors that break down the moment you try to use them for real work.

More posts by Adil

More in Programming

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto