F# · Lesson 9
Modules, Members and Classes
Organise code with modules, add members to records and unions, use interfaces, object expressions and classes, and call .NET APIs.
In short
module Name =groups functions;openimports them- A type plus a same-named module is a common pattern
- Members add properties and methods with dot access
- Interfaces are abstract members; object expressions implement them
- Classes for encapsulated state; records and modules for the rest
Modules: F#'s main unit of organisation
In TypeScript you group related functions in a file and export them. In F# you group them in a module:
// money.ts
export function fromCents(cents: number): number { return cents / 100; }
export function format(amount: number): string { return `$${amount.toFixed(2)}`; }
// elsewhere
import * as Money from "./money";
Money.format(Money.fromCents(1999)); // "$19.99"
module Money =
let fromCents (cents: int) : decimal = decimal cents / 100m
let format (amount: decimal) : string = sprintf "$%.2f" amount
Money.format (Money.fromCents 1999) // "$19.99"
open Money // like `import { fromCents, format }`
format 5m // "$5.00"
- Everything indented under
module Money =belongs to it. Modules can nest. let private helper ...hides a function from code outside the module.[<RequireQualifiedAccess>]on a module forbidsopen, so callers must writeMoney.format.- In a real project, a
.fsfile starts withmodule MyApp.Billing(no=, the whole file is the module) ornamespace MyApp.Billing(a namespace holds types and modules, but notletvalues directly). File order matters: the.fsprojlists files in order, and a file can only use what's defined above it. (The scripts in this app use themodule X =form only.)
A very common pattern is a type plus a module of the same name holding its functions:
type EmailAddress = EmailAddress of string
module EmailAddress =
let create (s: string) : Result<EmailAddress, string> =
if s.Contains "@" then Ok(EmailAddress s) else Error "invalid email"
let value (EmailAddress s) : string = s
Members on records and unions
Module functions are the default, but you can also attach members to a type. They give dot-completion
(order.Total) and a natural API for C# callers.
class Point {
constructor(public x: number, public y: number) {}
get length() { return Math.hypot(this.x, this.y); }
scale(k: number) { return new Point(this.x * k, this.y * k); }
static origin = new Point(0, 0);
}
type Point =
{ X: float
Y: float }
member this.Length = sqrt (this.X * this.X + this.Y * this.Y) // property
member this.Scale(k: float) = { X = this.X * k; Y = this.Y * k } // method
static member Origin = { X = 0.0; Y = 0.0 } // static property
let p = { X = 3.0; Y = 4.0 }
p.Length // 5.0
p.Scale(2.0) // { X = 6.0; Y = 8.0 }
Point.Origin // { X = 0.0; Y = 0.0 }
thisnames the current instance (any name works, and_when you don't use it:member _.Name = ...).- No parameters means a property; parameters in parentheses mean a method. Methods take C#-style tupled arguments:
p.Move(1.0, 2.0). static memberbelongs to the type itself:Point.Origin,Point.Create(...).
Unions can have members too. Match on this:
type Shape =
| Circle of radius: float
| Rect of width: float * height: float
member this.Area =
match this with
| Circle r -> System.Math.PI * r * r
| Rect(w, h) -> w * h
Interfaces and object expressions
interface Logger { log(message: string): void; }
const consoleLogger: Logger = { log: (m) => console.log(m) };
type ILogger =
abstract Log: message: string -> unit
let consoleLogger: ILogger =
{ new ILogger with
member _.Log(message) = printfn "%s" message }
consoleLogger.Log "hello"
abstractdeclares a member without a body. A type with only abstract members is an interface (theIprefix is the .NET convention).- An object expression
{ new IFace with member ... }creates an implementation on the spot, with no class needed. This is perfect for fakes in tests, and the closest thing to a TS object literal that satisfies an interface. - Multiple parameters are written tupled:
abstract Send: recipient: string * message: string -> bool.
Classes with primary constructors
class Counter {
private count: number;
constructor(public readonly name: string, start: number) {
if (start < 0) throw new Error("start must be >= 0");
this.count = start;
}
increment() { this.count++; return this.count; }
get current() { return this.count; }
}
type Counter(name: string, start: int) =
do
if start < 0 then
invalidArg (nameof start) "start must be >= 0"
let mutable count = start
member _.Name = name
member _.Current = count
member _.Increment() =
count <- count + 1
count
let c = Counter("visits", 10) // no `new` needed
c.Increment() |> ignore
c.Current // 11
Line by line:
type Counter(name: string, start: int) =declares the primary constructor. Its parameters are in scope in the whole class body.do ...runs when the object is constructed.invalidArgthrows anArgumentException.let mutable count = startis a private field. Everyletin a class is private.count <- count + 1assigns to a mutable value.member _.Increment(): the()makes it a method. Without it, it would be a property that runs (and increments!) every time it's read.- A class implements an interface with an
interface ILogger with member _.Log(m) = ...block. To call those members on a class instance you upcast:(myLogger :> ILogger).Log "hi".
Modules + functions vs classes
Most F# code is records and unions for data, module functions for behaviour. It's easy to test, easy to compose, and has no hidden state. Reach for classes when you need:
- encapsulated mutable state (a cache, a connection pool, a rate limiter);
- to implement a .NET interface or base class (
IDisposable, ASP.NET controllers, hosted services); - a service that receives dependencies through its constructor (dependency injection);
- a friendly API for C# consumers.
Rule of thumb: data goes in records/unions, logic in modules, and stateful boundaries in classes behind interfaces.
Calling .NET APIs
All of .NET is available. A few rules make it feel natural:
" Hello ".trim().toUpperCase();
["a", "b"].join(", ");
new Date(2024, 0, 31); // months are 0-based in JS!
open System
" Hello ".Trim().ToUpper() // "HELLO"
String.Join(", ", [ "a"; "b" ]) // "a, b"
let d = DateTime(2024, 1, 31) // months are 1-based
d.AddDays(1.0).ToString("yyyy-MM-dd") // "2024-02-01"
(DateTime(2024, 3, 1) - d).TotalDays // 30.0 (subtracting dates gives a TimeSpan)
let sb = Text.StringBuilder()
sb.Append("id-").Append(42) |> ignore // fluent methods return the builder; ignore it
sb.ToString() // "id-42"
- .NET methods take tupled arguments:
String.Join(", ", xs). With a single argument you may drop the parentheses (s.StartsWith "x"), but chained calls need them:s.Trim().ToUpper(). outparameters become tuples:Int32.TryParse "42"gives(true, 42).- Methods aren't curried, so you can't partially apply
s.Replace("a"). Wrap them in a lambda instead. - Type inference flows left to right.
List.map (fun s -> s.Length) namesfails to compile, whilenames |> List.map (fun s -> s.Length)works because the type ofsis known by then.
Units of measure (briefly)
[<Measure>] type kg
[<Measure>] type m
let weight = 72.5<kg>
let height = 1.8<m>
let bmi = weight / (height * height) // float<kg/m^2>
// weight + height // compile error: kg and m don't mix
Units exist only at compile time (zero runtime cost). They're handy for currencies, distances and durations. float weight strips the unit.
Common beginner mistakes
- Using something defined further down (or in a later file). F# only sees what's above.
- Forgetting
()on a no-argument method.member _.Reset = ...is a property and runs on every read. - Calling an interface member on a class without upcasting. Use
(account :> IAccount).Balance, or type the value as the interface. - Mixing call styles. Methods are
obj.Method(a, b), functions aref a b. - Ignoring return values of fluent .NET APIs.
sb.Append "x"alone gives warning FS0020. Add|> ignore. - Writing a class for everything, as you might in TS or C#. Start with a record and a module.
- Using
neweverywhere. Only use it forIDisposableobjects (use reader = new StreamReader(path)).
Cheat sheet
module Billing = // group functions
let private helper x = x // hidden outside the module
type Point = { X: float; Y: float } // ...then indent members under it:
member this.Length = ... // property
member _.Move(dx: float, dy: float) = ... // method (tupled args)
static member Create(x, y) = ... // Point.Create(1.0, 2.0)
type IClock = abstract Now: DateTime // interface
{ new IClock with member _.Now = DateTime(2024, 1, 1) } // object expression
type Account(owner: string) = // class + primary constructor
let mutable balance = 0m // private state
member _.Deposit(x: decimal) = balance <- balance + x
(x :> IClock).Now // upcast to an interface
[<Measure>] type usd // units of measure: 10m<usd>
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