liveBook · Manning

Conditional logic

As explained in F# in Action: A Revised Edition of Get Programming with F#

A conditional is a programming construct that selects execution or generated content based on a Boolean condition.

Conditional logic chooses between alternatives, but statement-oriented if/then code can leave cases uncovered, assign the wrong variable, or require unsafe defaults. Expression-oriented branching makes the result explicit. section 4.1.2 section 4.1.4

Listing 4.3 Working in an expression-oriented language
let describeAge age =
    let ageDescription =             #1
        if age < 18 then "Child"     #2
        elif age < 65 then "Adult"
        else "OAP"
    let greeting = "Hello"
    $"{greeting}! You are a '{ageDescription}'."

An F# if/then expression returns a value, so each branch supplies the same result type and can initialize a binding directly. section 4.1.4

Deriving a description

let describeAge age = let ageDescription = if age < 18 then "Child" elif age < 65 then "Adult" else "OAP" $"Hello! You are a '{ageDescription}'." section 4.1.4

Choose the conditional form that matches the operation:

  • Use if/then when directly testing a Boolean; it is shorter and easier to read than matching true and false. section 8.2.5
  • Use if/else for a unit-returning side effect when no action is needed in the false case; the catch-all else () can be omitted. section 8.2.5
  • Use pattern matching when conditional logic needs to inspect broader value shapes or cases. section 8.2.5 section 8.0

Because F# treats virtually everything as an expression, conditional branches participate in value construction, immutability, function results, and domain-modeling code rather than merely controlling program flow. section 4.1.4 section 8.4

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Explains expression results, same-typed branches, immutability, and unit-returning exceptions; contrasts if/then with pattern matching.
Examples
Uses age descriptions, Boolean selection, and saving a modified order request.
What you can do after
Apply it via F# if/then expressions to derive values and guard side effects.
How it connects
Connects conditional logic to expressions, pattern matching, discriminated unions, the type system, and domain modeling.

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 F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.