liveBook · Manning

Conditional logic

As explained in Learn Haskell by Example

An if-then-else expression is a conditional expression that evaluates one of two branches based on a Boolean condition and must produce a value.

Conditional logic chooses between two expressions using a Boolean condition. In Haskell, if-then-else is an expression, so both branches are required and must produce a usable value. section 2.4.3

Use conditional expressions when a function or action must choose between alternatives:

  • Write `if condition then expression1 else expression2`; an if without else is invalid because it might not evaluate to a value. section 2.4.3
  • Keep both branches compatible. In an IO action, both branches must evaluate to actions of the same type, such as `IO ()`. section 3.1.3 section 3.5
  • Replace deeply nested conditionals with guards when several Boolean cases make the function difficult to read. section 2.4.3

Choosing a character transformation

A character rotation function can preserve nonletters while selecting different helpers for lowercase and uppercase input: `rotChar n ch = if isLower ch then lowerRot n ch else if isUpper ch then upperRot n ch else ch`. For example, rotating `'A'` by 13 produces `'N'`, while rotating `'1'` preserves `'1'`. section 2.4.3

ghci> x = 10 :: Int
ghci> if x > 5 then "x is larger than 5" else "x is not larger than 5"
"x is larger than 5"

Evaluate a conditional directly in GHCi and observe that the selected branch produces a string value. section 2.4.3

How Learn Haskell by Example covers it

How deep it goes
Defines value-producing branches and same-type IO branches, then limits nested conditionals before introducing guards.
Examples
Uses character rotation, empty-line detection, GHCi evaluation, and recursive input echoing.
What it assumes
Assumes Boolean expressions and basic functions; teaches mandatory else branches and action typing through examples.
What you can do after
Apply it via Haskell expressions to choose pure values or sequence IO actions safely.
How it connects
Connects Boolean expressions, guards, recursion, do notation, IO actions, and return.

Also explained in

Compare how 21 books explain conditional logic →

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.