Hello World in F#
Your first F# program - the classic Hello World example with Docker setup
Every programming journey starts with Hello World. Let’s write our first F# program and see how clean and expressive functional programming can be.
The Code
Create a file named hello.fsx:
| |
That’s it! F# is incredibly concise. The .fsx extension indicates an F# script file that can be run directly without compilation.
Understanding the Code
printfn- A formatted print function that writes to the console and adds a newline- F# scripts - Files ending in
.fsxcan be run directly with F# Interactive (fsi) - No semicolons needed - F# is expression-oriented and whitespace-sensitive
Alternative: Compiled F# Program
If you want to create a compiled program instead of a script, create a file named Program.fs:
| |
For beginners, the script version is simpler. For production applications, you’d use compiled .fs files.
Running with Docker
The easiest way to run F# without installing the .NET SDK locally is using Docker:
| |
The dotnet fsi command runs F# Interactive, which executes your script file.
Running Locally
If you have the .NET SDK installed (version 6.0+):
For F# Scripts (.fsx):
| |
For Compiled F# Projects:
| |
Expected Output
Hello, World!
Key Concepts
- F# is functional-first - Functions and immutability are the default approach
- Type inference - The compiler figures out types for you
- Two modes - Scripts (
.fsx) for quick experimentation, compiled (.fs) for applications - F# Interactive (fsi) - REPL for interactive development and testing
- Part of .NET - Runs on the same runtime as C# with full interoperability
F# Interactive (REPL)
F# includes a powerful REPL (Read-Eval-Print Loop) that makes exploration easy:
| |
You can type expressions and see results immediately:
| |
This interactive development style is one of F#’s strengths!
Why printfn?
F# uses printfn instead of print because it supports printf-style formatting:
| |
The f stands for “formatted,” and the n means “newline.” There’s also printf (no newline) and sprintf (returns a string).
Comparison with Other Languages
If you’re coming from other languages, here’s how F# compares:
Python:
| |
C#:
| |
F#:
| |
F# strikes a balance - concise like Python, but with the power and performance of .NET like C#.
Next Steps
Now that you’ve written your first F# program, you’re ready to explore:
- Variables and immutability - How F# handles data
- Functions - The heart of functional programming
- Pattern matching - F#’s powerful control flow
- Type inference - Writing less code while staying type-safe
F# is a language that grows with you. Start simple, and gradually discover the power of functional programming on .NET!
Running Today
All examples can be run using Docker:
docker pull mcr.microsoft.com/dotnet/sdk:9.0