Skip to content
LumenaryAcademy
Foundations 50 min

First steps with F#

Where F# comes from, what "functional-first" means, and your first scripts in F# Interactive.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Why F#?

Most programming languages you meet first are imperative: a program is a list of commands that change variables, one after another. F# starts from a different idea. A program is mostly made of expressions that compute values from other values, and of functions that turn inputs into outputs, with as little changing of things as possible. Code written this way is easier to test (a function's result depends only on its inputs), easier to run in parallel (nothing is being changed underneath you), and often much shorter.

F# is functional-first, not functional-only. When a loop with a mutable counter is clearer, you can write one. When you need a class to talk to a .NET library, you can define one. And because F# runs on .NET, every library written for C# is available to you: web frameworks, database drivers, cloud SDKs, machine-learning libraries.

Where is F# used? In finance (pricing, risk and trading systems, where correctness and concise modelling matter), in data science and scientific computing, in compilers and developer tools, in business software with complicated rules, in web services, and in teaching. Its community is smaller than C#'s, and its users tend to be enthusiastic about it for a concrete reason: programs that compile usually work, because F#'s types can describe a problem precisely.

History & global context

From ML to F# 10

F#'s family tree starts with ML, a language created in the 1970s by Robin Milner and colleagues at the University of Edinburgh as the "meta language" of a theorem prover. ML introduced two ideas that every language in the family shares: type inference (the compiler works out types you did not write) and algebraic data types with pattern matching. In France, researchers at INRIA developed the Caml dialect and later OCaml, which added objects and a fast native compiler.

At Microsoft Research in Cambridge, Don Syme had worked on adding generics to .NET, the feature C# gained in version 2. He then set out to bring an OCaml-like language to .NET, so that functional programmers could use its libraries and .NET programmers could use functional ideas. The first version of F# was released in 2005. It became a supported part of Visual Studio in 2010 (F# 2.0), its compiler and core library were open-sourced, and the independent F# Software Foundation was formed to support the community. Today the language is developed in the open on GitHub, with Microsoft and community contributors, and new features are proposed and specified as public RFCs.

F# has been an influential neighbour. Its asynchronous workflows (2007) were a direct inspiration for C#'s async and await, and ideas such as records, pattern matching and immutable-by-default data have since moved into C# as well. F# 3.0 (2012) introduced type providers, which generate types from external data sources at compile time.

A new F# version ships with each yearly .NET release. This course teaches F# 10, which shipped with .NET 10 in November 2025, the current long-term-support release; F# 11 followed with .NET 11 in November 2026. Almost everything here works in earlier versions too, and the lessons point out what is recent.

IntuitionH

Expressions, bindings and immutability

Three ideas make F# code look the way it does.

Definition— Let binding

let name = expression evaluates the expression and gives its value a name. The binding is immutable: the name refers to that value for as long as it is in scope. Inside a function (or at the interactive prompt), writing let again with the same name creates a new binding that shadows the old one; it does not change the old value. At the top level of a file, each name may be defined only once.

Everything is an expression. In C# or Python, if is a statement that does something. In F#, if ... then ... else ... is an expression that has a value, like the conditional operator in other languages, so you can bind it directly: let size = if population > 100_000 then "city" else "town". Blocks of code are expressions too: their value is the value of their last line. There is no return keyword; a function returns the value of its body.

Indentation is structure. F# uses the layout of the code, not braces, to show what belongs inside what, as Python does. Lines that belong to a function body are indented under its let. Tabs are not allowed; use spaces (four is conventional).

Types are inferred, but static. You rarely write types, yet every value has one, fixed at compile time. let square x = x * x is inferred to take and return an int. The tools show you the inferred types as you write, and you can always add annotations when they help a reader: let square (x: int) : int = x * x.

Analogy, not a formal construction

A let binding is like writing a value in ink on a labelled card, while a mutable variable is a whiteboard. You can always make a new card with the same label, but nobody can secretly change what is written on the card you are holding. Code that passes cards around is much easier to reason about than code where anyone might wipe the whiteboard.

ComputationC

Running F#

Install the .NET 10 SDK from the official download page (the course page links it). F# comes with it; there is nothing extra to install. Then you have three ways to run F#.

F# Interactive

Type dotnet fsi to start F# Interactive, a REPL (read-evaluate-print loop). Type an expression, end it with two semicolons, and press Enter:

text
> let square x = x * x;;
val square: x: int -> int

> square 12;;
val it: int = 144

F# Interactive prints the type of everything you define: here, square is a function from int to int. Professionals use it constantly to try ideas, explore data and test a function before putting it into a project. Editors can send a selected piece of code to it with a keystroke.

Scripts

Save code in a file ending in .fsx and run it with dotnet fsi:

bash
dotnet fsi hello.fsx
fsharp
printfn "Hello, world!"
printfn "Salaam, dunya!"

It prints:

text
Hello, world!
Salaam, dunya!

printfn prints a line. Scripts are perfect for automation, data exploration and learning, and they can pull in NuGet packages with a directive such as #r "nuget: FSharp.Data". (The ;; is needed only when typing into the interactive prompt.)

Projects

Applications live in projects. dotnet new console -lang F# -o Greeter creates a folder with Program.fs and a project file:

xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Program.fs" />
  </ItemGroup>

</Project>

dotnet run builds and runs it, just as for C#. Notice the Compile list. Unlike C#, F# compiles files in the order the project lists them, and a file can use only what is defined above it or in earlier files. Newcomers find this strange; experienced F# developers consider it a feature, because it rules out circular dependencies and lets you read a codebase from top to bottom. Editors let you reorder files easily.

Worked examplesH

Your first real F# programs

This script shows bindings, a conditional expression, functions and formatted printing:

fsharp
// Values are immutable by default: a let binding names a value, once.
let town = "Lakeside"
let population = 52_400
let areaKm2 = 31.4

// Everything is an expression, including if/then/else.
let density = float population / areaKm2
let size = if population > 100_000 then "city" else "town"

printfn "%s is a %s of %d people" town size population
printfn "Density: %.1f people per km²" density

// Functions are values too. Types are inferred.
let square x = x * x
let greet name = $"Xin chào, {name}!"

printfn "%d" (square 12)
printfn "%s" (greet "Linh")

// Shadowing makes a new binding with the same name; nothing is mutated.
let total = 10
let total' = total + 5
printfn "total = %d, total' = %d" total total'

It prints:

text
Lakeside is a town of 52400 people
Density: 1668.8 people per km²
144
Xin chào, Linh!
total = 10, total' = 15
  • Numeric types do not mix silently. population is an int and areaKm2 a float (F#'s name for a 64-bit floating-point number, the same as C#'s double). F# never converts between them automatically, so float population converts explicitly. This strictness catches real bugs.
  • printfn uses type-checked format specifiers: %s for strings, %d for integers, %.1f for a float with one decimal place, and %A for any value in a readable form. Get the type wrong (%d with a string) and the program does not compile.
  • Interpolated strings start with $ and put expressions in braces, as in C#. Typed holes such as %d{count} are also allowed inside them.
  • Function application uses spaces, not parentheses: square 12, greet "Linh". Parentheses only group: printfn "%d" (square 12) passes the result of square 12 to printfn.
  • total' is a legal name: F# allows a trailing apostrophe, read "total prime", for a value derived from another.

Indentation, loops and the rare mutable

fsharp
// Indentation, not braces, shows structure.
let describeTemperature celsius =
    let fahrenheit = celsius * 9.0 / 5.0 + 32.0
    let feel =
        if celsius < 0.0 then "freezing"
        elif celsius < 15.0 then "cool"
        elif celsius < 25.0 then "pleasant"
        else "hot"
    sprintf "%5.1f °C = %5.1f °F (%s)" celsius fahrenheit feel

for c in [ -5.0; 12.0; 21.5; 34.0 ] do
    printfn "%s" (describeTemperature c)

// When you really need mutation, you must say so.
let mutable count = 0
for word in [ "luna"; "terra"; "mare"; "sol" ] do
    if word.Length = 4 then
        count <- count + 1
printfn "%d words have four letters" count

It prints:

text
 -5.0 °C =  23.0 °F (freezing)
 12.0 °C =  53.6 °F (cool)
 21.5 °C =  70.7 °F (pleasant)
 34.0 °C =  93.2 °F (hot)
2 words have four letters

describeTemperature has local bindings (fahrenheit, feel) indented inside it; its value is its last line, the sprintf call, which formats a string the way printfn prints one. if/elif/else is one expression choosing among four strings. [ -5.0; 12.0; 21.5; 34.0 ] is a list, with elements separated by semicolons, and for ... in ... do loops over it.

The last part shows that mutation is possible, but explicit: let mutable declares a variable that can change, and <- assigns to it. The = sign is never assignment in F#; outside a let, it is the equality test, which is why word.Length = 4 compares. In idiomatic F#, mutable variables are rare and local. The next lessons show how to count, filter and accumulate without them.

ExplanationH

How F# developers work

Editors. The three main choices are Visual Studio Code with the Ionide extension (free, community-built, on every operating system), JetBrains Rider, and Visual Studio on Windows. All show inferred types inline as you write, which is how you learn to read F#'s types quickly: hover over any name and the editor tells you exactly what the compiler believes it is.

REPL-driven development. A typical F# workflow is to sketch a function in a script, send it to F# Interactive, try it on a few inputs, refine it, and only then move it into a project file. Because functions are small and mostly free of side effects, trying them in isolation is easy, and the habit catches many mistakes before any test is written.

Small files in order. A project is a short, ordered list of files: domain types first, then the functions that work on them, then the code that talks to the outside world, and the program's entry point last. Reading a well-organised F# project from top to bottom tells you its story.

FSharp.Core. Every F# program uses the FSharp.Core library, which provides lists, options, results, the List, Seq, Array and Map modules, printfn and asynchronous workflows. It is versioned with the compiler and ships as a NuGet package, so C# projects can use it too.

Style. The official F# style guide (part of the documentation) and the Fantomas formatter, covered in the last lesson, keep code consistent across a team.

Common misconceptionsH

Common misconceptions

Misconception

"F# is an academic language for mathematicians." It came from research, but it was designed for practical work on an industrial platform, and it is used in production for finance, logistics, healthcare, games tooling and web services. You do not need any mathematics beyond what ordinary programming needs.

Misconception

"Functional programming means you can never change anything." F# makes immutability the default and mutation explicit, and it lets you use arrays, mutable variables, dictionaries and classes when they are the right tool. The aim is to make change visible and contained, not forbidden.

Misconception

"F# can't use the C# libraries my team depends on." F# and C# compile to the same IL and run on the same runtime. An F# project can reference any NuGet package or C# project, and C# can call F# libraries. A later lesson covers the details.

Misconception

"Without type annotations, F# must be dynamically typed." Every value has a static type, inferred by the compiler. Change a function so it returns a string instead of a number and every caller that expected a number fails to compile.

Exercises

Exercises

Work out each answer before running anything. To check, save the code as a .fsx file and run it with dotnet fsi.

1. First steps with F#

Warm-upComputational

What does this script print?

let describe n = if n % 2 = 0 then "even" else "odd"

let report () =
    let x = 10
    let x = x * 3 + 1
    $"{x} is {describe x}"

printfn "%s" (report ())

2. First steps with F#

Warm-upComputational

What does this script print?

let mutable total = 0
for n in [ 3; 8; 5; 10; 2 ] do
    if n > 4 then
        total <- total + n
printfn "%d" total

3. First steps with F#

CoreComputational

What does this script print?

let label score =
    let grade =
        if score >= 90 then "A"
        elif score >= 75 then "B"
        else "C"
    $"{score}:{grade}"

printfn "%s %s %s" (label 90) (label 89) (label 74)

4. First steps with F#

CoreHuman

What happens when you run this script?

let a = 3
let b = 2.0
printfn "%f" (a * b)
Choose one

5. First steps with F#

CoreComputational

What is the first line printed by this script?

printfn "%.2f" (float 7 / 2.0)
printfn "%d" (7 / 2)

6. First steps with F#

CoreHuman

An F# project lists its files in this order: Domain.fs, Pricing.fs, Program.fs. Which statement is true?

Choose one

Further reading and resources