Your First Program
Prerequisites: Installing F#
Create a file named hello.fsx:
printfn "Hello, world!"
printfn "Welcome to F#."
Run it:
dotnet fsi hello.fsx
Expected output
Hello, world!
Welcome to F#.
printfnprints text followed by a new line;printfprints without the new line.- Strings go in double quotes.
- No semicolons, no braces, no
mainfunction: a script runs from top to bottom.
Format specifiers
printfn takes a format string with placeholders, and checks the
arguments' types at compile time:
let name = "Ada"
let age = 36
printfn "%s is %d years old" name age
printfn "Pi is roughly %.2f" 3.14159
printfn "Anything: %A" [1; 2; 3]
printfn $"Interpolated: {name} is {age}"
Ada is 36 years old
Pi is roughly 3.14
Anything: [1; 2; 3]
Interpolated: Ada is 36
%s is a string, %d an integer, %f a float (%.2f with two
decimals), and %A pretty-prints any value. The last line uses an
interpolated string — $"..." with expressions in braces.
A console project
For a real application, create a project:
dotnet new console -lang F# -o HelloApp
cd HelloApp
dotnet run
The template's Program.fs contains a single line,
printfn "Hello from F#", which is what dotnet run prints.
Practice
Write a script that prints your name on one line and, on the next line,
the sentence "I am learning F#" using a %s placeholder for the word
"F#".
Show solution
printfn "Ada"
printfn "I am learning %s" "F#"
Ada
I am learning F#