liveBook · Manning

Statement

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

A statement is a program construct that performs an action or controls execution without necessarily evaluating to a usable value.

A statement performs an action or controls execution without returning a usable value. Statement-oriented code commonly combines branching, assignments, and side effects, making missing cases or incorrect assignments easy to overlook. section 4.1.2 section 4.1

Statements differ from expressions in several practical ways:

  • They never return a value; their effects come from changing state or calling external systems. section 4.3 section 4.1
  • Their branches are treated as separate execution paths, so the compiler may not recognize that every branch should produce related data. section 4.1.3
  • They can require default values and repeated assignments, leaving room for missing cases, wrong-variable assignments, and null results. section 4.1.2

Replacing branch assignments with a result

A statement-oriented age description initializes a variable, assigns it in selected branches, and prints whatever remains. An expression-oriented version makes each branch return a string: if age < 18 then "Child" elif age < 65 then "Adult" else "OAP". The result is assigned once, so the catch-all case and the intended destination are explicit. section 4.1.2 section 4.1.4

Listing 4.1 Working in a statement-oriented language
using System;
 
public void DescribeAge(int age)
{
    string ageDescription = null;    #1
    var greeting = "Hello";          #2
    if (age < 18)
        ageDescription = "Child";    #3
    else if (age < 65)
        greeting = "Adult";          #4
 
    Console.WriteLine($"{greeting}! You are a '{ageDescription}'.");
}

Inspect the age-description example to see how initialization, conditional assignments, and output combine into a statement-oriented flow. section 4.1.2

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

How deep it goes
Defines statements by their missing return value and side effects, then examines branching bugs before contrasting expressions.
Examples
Uses an age-description conditional, a flow diagram, and an exercise distinguishing statements from expressions.
What you can do after
Evaluate code by distinguishing value-producing expressions from effectful statements and spotting incomplete or unsafe branch assignments.
How it connects
Connects statements with expressions, control flow, side effects, mutable state, and immutability.

Also explained in

Compare how 3 books explain statement →

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.