F# · Lesson 1

Basics

let bindings, immutability, primitive types, string formatting and if/else as expressions.

8 min read

In short

  • let is const; let mutable and <- for the rare variable
  • No mixing number types in arithmetic: convert with float, int, decimal, string
  • Functions take space-separated arguments; the last expression is the result
  • if/then/else is an expression, and = compares
  • Use decimal for money and watch integer division

F# is a functional-first language on .NET. If you know TypeScript you already know most of the ideas (type inference, union types, arrow functions, map/filter). What is new is the syntax and a few strong defaults: values are immutable, almost everything is an expression, and whitespace matters.

How your code runs here

Every exercise is an F# script (.fsx) run with dotnet fsi. The file runs top to bottom and the tests are appended after your code. There is no main, no export and no import to write.

One big difference from TypeScript: order matters. You can only use something that is defined above the line you are on. There is no hoisting.

let: naming a value

▶ Try
let taxRate = 0.2
let storeName = "Corner Shop"
let itemCount = 3
▶ Try
const taxRate = 0.2;
const storeName = "Corner Shop";
const itemCount = 3;

Line by line: let starts a binding, then the name, =, and an expression. No semicolons, no const. A let binding is immutable: it is a const, always.

Watch out: taxRate = 0.3 on its own line does not assign anything. Outside a let, = is the equality operator (TypeScript's ===), so that line just computes false. Inside a function the compiler warns that the result is ignored.

Inside a function you may shadow a name by binding it again. This creates a new value; nothing is mutated. (At the top level of a script, defining the same name twice is an error.)

▶ Try
let priceWithTax (price: float) : float =
    let price = price * 1.2   // a new `price` hides the parameter
    price

mutable and <-

When you really need a variable, ask for one explicitly and assign with <-:

▶ Try
let mutable count = 0
count <- count + 1
▶ Try
let count = 0;
count = count + 1;

Mutable locals are fine inside a function (for example, a loop counter), but idiomatic F# reaches for expressions and collection functions first. You'll see far less mutable than you'd see let in TS.

A for loop looks like this:

▶ Try
let mutable total = 0
for n in 1 .. 10 do
    total <- total + n
// total = 55

Primitive types

F# typeLiteralTypeScriptNotes
int42, -7number32-bit integer
float3.14, 2.0number64-bit double. Needs a .
decimal19.99m(none)Exact base-10, use for money
int6442Lbigint-ish64-bit integer
string"hello"string.NET string
char'a'(none)Single character, single quotes
booltrue, falseboolean
unit()void"No meaningful value"

F# never mixes number types in arithmetic. 1 + 2.0 is a compile error. (Since F# 6 an int is widened when the target type is already known, such as passing 3 to a float parameter, but arithmetic never mixes types.) Convert explicitly with functions named after the type:

▶ Try
let quantity = 3
let unitPrice = 2.5
let total = float quantity * unitPrice   // 7.5
let whole = int 3.9                      // 3 (truncates)
let half = 7 / 2                         // 3: int / int is integer division
let exactHalf = 7.0 / 2.0                // 3.5
let asText = string 42                   // "42"

Type inference and annotations

F# infers types like TypeScript does, but even more aggressively: usually you write no types at all.

▶ Try
let add a b = a + b                       // inferred: int -> int -> int
let addPrices (a: float) (b: float) : float = a + b
▶ Try
function addPrices(a: number, b: number): number { return a + b; }

Reading the F# version:

  • let addPrices defines a function because it has parameters.
  • Each parameter is separated by spaces, not commas. (a: float) annotates one parameter.
  • : float after the parameters is the return type.
  • The body follows =. The last expression is the return value. There is no return keyword.

You call it the same way, with spaces: addPrices 1.5 2.0. If an argument is itself a call, wrap it in parentheses: addPrices (addPrices 1.0 2.0) 3.0.

Multi-line bodies are indented; local values are just more lets:

▶ Try
let totalWithTax (net: float) : float =
    let taxRate = 0.2
    let tax = net * taxRate
    net + tax

Strings and formatting

▶ Try
let name = "Ada"
let greeting = "Hello, " + name                 // concatenation
let message = $"Hello, {name}!"                 // interpolation, like `Hello, ${name}!`
let price = 4.5
let label = $"Price: %.2f{price}"               // "Price: 4.50" (typed format specifier)
let line = sprintf "%s owes %.2f" name price    // sprintf returns a string
printfn "Total: %d items" 3                     // printfn prints + newline

sprintf and printfn take a format string and then the values as separate arguments. The format specifiers are type-checked, so sprintf "%d" "oops" does not compile.

SpecifierTypeExample
%d / %iintegerssprintf "%d" 42 → "42"
%f, %.2ffloat / decimalsprintf "%.2f" 3.14159 → "3.14"
%sstringsprintf "%s!" "hi" → "hi!"
%bbool"true" / "false"
%ccharsprintf "%c" 'x'
%Mdecimalsprintf "%M" 9.99m
%Aanything (pretty print)lists, records, tuples
%5d, %-10spaddingright / left aligned

Strings are .NET strings, so all the methods you'd expect exist: s.Length, s.ToUpper(), s.Trim(), s.Contains("x"), s.StartsWith("x"), s.Replace("a", "b"), s.Split(','). Index with s[0] (a char).

if / then / else is an expression

▶ Try
let label = if count = 1 then "item" else "items"

let grade (score: int) : string =
    if score >= 90 then "A"
    elif score >= 75 then "B"
    else "C"
▶ Try
const label = count === 1 ? "item" : "items";

Because if produces a value, both branches must have the same type, and an if without else is only allowed when the branch returns unit. Comparison operators: = (equals), <> (not equals), <, <=, >, >=. Logic: &&, ||, not.

unit and ()

unit has exactly one value, written (). It plays the role of void:

▶ Try
let sayHi () = printfn "hi"   // unit -> unit: takes nothing, returns nothing
sayHi ()                      // call it with ()
ignore (addPrices 1.0 2.0)    // `ignore` throws a value away, returning ()

Indentation (the offside rule)

Like Python, F# uses indentation instead of { }. Everything that belongs to a let, if or loop must be indented further than the line that started it. Use spaces (4 is the convention); tabs are not allowed.

Comments

▶ Try
// line comment
(* block comment *)
/// XML doc comment: shows up in editor tooltips

Common beginner mistakes

  • Reassigning with =. total = total + 1 is a comparison. Use let mutable total and total <- total + 1.
  • Calling with commas. addPrices(1.0, 2.0) passes one tuple argument and fails to compile. Write addPrices 1.0 2.0.
  • Mixing int and float. let average = sum / count where sum is float and count is int won't compile. Write sum / float count. And remember 7 / 2 = 3.
  • Integer literals where a float is needed. price * 2 fails if price is a float: write 2.0.
  • if without else returning a value. let x = if ok then "yes" is an error. Add an else.
  • Using == or !=. F# uses = and <>.
  • Negative arguments. abs -3 works, but f x -1 is easy to misread. Prefer f x (-1).
  • Method call on an unknown type. let shout s = s.ToUpper() fails with "Lookup on object of indeterminate type". Annotate: let shout (s: string) = s.ToUpper().
  • Forgetting () on a unit function. sayHi is the function itself; sayHi () calls it.
  • Bad indentation. If the compiler complains about "offside" or "possible incorrect indentation", line the body up under the start of the expression, 4 spaces in.

Cheat sheet

▶ Try
let x = 5                              // immutable binding (const)
let mutable n = 0                      // mutable variable
n <- n + 1                             // assignment
let f (a: int) (b: int) : int = a + b  // function with annotations
f 1 2                                  // call: spaces, no commas
float 3 / 2.0                          // explicit conversions: float, int, decimal, string
$"Hi {name}, total %.2f{total}"        // interpolation (+ typed format)
sprintf "%s: %d" name count            // formatted string
printfn "%A" anything                  // print anything
if a = b then "same" elif a < b then "less" else "more"   // expression
a <> b                                 // not equal
let doIt () = ()                       // unit
for i in 1 .. 10 do printfn "%d" i     // loop

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app