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



