Lesson 7. Expressions and statements

 

Expressions and statements are two aspects of programming that we use often, and generally take for granted, but in F# the distinction between the two is much starker than you might be used to. In this lesson, you’ll do the following:

  • Explore the differences between statements and expressions
  • Lean the pros and cons of both
  • See how expressions in combination with the F# type system and compiler can help you write code that’s more succinct as well as easier to reason about

7.1. Comparing statements and expressions

Before we dive in, let’s quickly recap the definitions of statements and expressions. Here are two definitions taken directly from the C# documentation on MSDN—first statements, and then expressions:

The actions that a program takes are expressed in statements. Common actions include declaring variables, assigning values, calling methods, looping through collections, and branching to one or another block of code, depending on a given condition.

An expression is a sequence of one or more operands and zero or more operators that can be evaluated to a single value, object, method, or namespace.

One of these is written in relatively plain (but somewhat verbose) English. The other is plain confusing (to me, at least!). Let’s redefine the two terms more succinctly and appropriately for this purposes of this lesson; see table 7.1.

7.2. Using expressions in F#

7.3. Forcing statement-based evaluation

Summary

sitemap