F# · Lesson 1
Basics
let bindings, immutability, primitive types, string formatting and if/else as expressions.
In short
letisconst;let mutableand<-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/elseis an expression, and=compares- Use
decimalfor 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
let taxRate = 0.2
let storeName = "Corner Shop"
let itemCount = 3
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.3on its own line does not assign anything. Outside alet,=is the equality operator (TypeScript's===), so that line just computesfalse. 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.)
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 <-:
let mutable count = 0
count <- count + 1
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:
let mutable total = 0
for n in 1 .. 10 do
total <- total + n
// total = 55
Primitive types
| F# type | Literal | TypeScript | Notes |
|---|---|---|---|
int | 42, -7 | number | 32-bit integer |
float | 3.14, 2.0 | number | 64-bit double. Needs a . |
decimal | 19.99m | (none) | Exact base-10, use for money |
int64 | 42L | bigint-ish | 64-bit integer |
string | "hello" | string | .NET string |
char | 'a' | (none) | Single character, single quotes |
bool | true, false | boolean | |
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:
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.
let add a b = a + b // inferred: int -> int -> int
let addPrices (a: float) (b: float) : float = a + b
function addPrices(a: number, b: number): number { return a + b; }
Reading the F# version:
let addPricesdefines a function because it has parameters.- Each parameter is separated by spaces, not commas.
(a: float)annotates one parameter. : floatafter the parameters is the return type.- The body follows
=. The last expression is the return value. There is noreturnkeyword.
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:
let totalWithTax (net: float) : float =
let taxRate = 0.2
let tax = net * taxRate
net + tax
Strings and formatting
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.
| Specifier | Type | Example |
|---|---|---|
%d / %i | integers | sprintf "%d" 42 → "42" |
%f, %.2f | float / decimal | sprintf "%.2f" 3.14159 → "3.14" |
%s | string | sprintf "%s!" "hi" → "hi!" |
%b | bool | "true" / "false" |
%c | char | sprintf "%c" 'x' |
%M | decimal | sprintf "%M" 9.99m |
%A | anything (pretty print) | lists, records, tuples |
%5d, %-10s | padding | right / 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
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"
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:
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
// line comment
(* block comment *)
/// XML doc comment: shows up in editor tooltips
Common beginner mistakes
- Reassigning with
=.total = total + 1is a comparison. Uselet mutable totalandtotal <- total + 1. - Calling with commas.
addPrices(1.0, 2.0)passes one tuple argument and fails to compile. WriteaddPrices 1.0 2.0. - Mixing
intandfloat.let average = sum / countwheresumisfloatandcountisintwon't compile. Writesum / float count. And remember7 / 2 = 3. - Integer literals where a float is needed.
price * 2fails ifpriceis afloat: write2.0. ifwithoutelsereturning a value.let x = if ok then "yes"is an error. Add anelse.- Using
==or!=. F# uses=and<>. - Negative arguments.
abs -3works, butf x -1is easy to misread. Preferf 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.sayHiis 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
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