liveBook · Manning

Guard

As explained in Learn Haskell by Example

A guard is a conditional expression attached to a function or pattern definition that selects a case when its Boolean condition holds.

A guard attaches a Boolean condition to a function definition. Haskell evaluates guarded cases in order and chooses the first condition that holds, making guards a readable alternative to nested if-then-else expressions. section 2.4.3 section 2.6

Classifying characters for rotation

A character-rotation function can select the appropriate transformation without nested conditionals: rotChar :: Int -> Char -> Char rotChar n ch | isLower ch = lowerRot n ch | isUpper ch = upperRot n ch | otherwise = ch The first guard handles lowercase characters, the second handles uppercase characters, and otherwise preserves every other character. For example, rotChar 13 'A' produces 'N', while rotChar 10 '1' produces '1'. section 2.4.3

When writing guarded definitions:

  • Use any Boolean expression as a guard. section 2.4.3
  • Put more specific cases before broader cases because guards are tested in order. section 2.4.3
  • Finish with otherwise when the function needs a default case; otherwise is a synonym for True. section 2.4.3
Listing 2.10 Rotation function for arbitrary characters
rotChar :: Int -> Char -> Char
rotChar n ch
  | isLower ch = lowerRot n ch     #1
  | isUpper ch = upperRot n ch     #2
  | otherwise = ch   #3

Inspect the complete guarded rotation definition and its ordered character cases. section 2.4.3

How Learn Haskell by Example covers it

How deep it goes
Defines syntax, Boolean matching, ordering, and default cases, but does not descend into compiler implementation.
Examples
Demonstrates character rotation for lowercase, uppercase, and non-letter inputs.
What it assumes
Uses Boolean expressions and basic function definitions while introducing guards as a Haskell case-distinction technique.
What you can do after
Build it from scratch by replacing nested conditionals with ordered Boolean cases and a default guard.
How it connects
Connects Boolean predicates with pattern matching and contrasts guards with if-then-else expressions.

Also explained in

Compare how 4 books explain guard →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.