F#, lesson 1
F# is a functional-first language that runs on .NET. It has a strong static type system, so the compiler checks your program before it runs, yet you rarely have to write types yourself. Let's start by printing something.
printfn prints its text and then moves to a new line. Text in double quotes is a string.
Notice that there are no parentheses: in F# you call a function by writing its name followed by
its arguments, separated by spaces.
printf (no n) prints and stays on the same line. The next print continues right after it:
The first argument of printf and printfn is a format string. It can contain
placeholders that are filled with the values that follow:
| Placeholder | Type |
|---|
2 exercises to try what you just read.
%s | string |
%d | integer |
%f | floating-point number (%.2f for 2 decimals) |
%b | true / false |
%A | any value, in a readable form |
The compiler checks the format: passing a string where %d expects a number is a compile
error, not a mistake you discover later.
// starts a comment that runs to the end of the line. (* ... *) is a block comment that can
span several lines.
F# uses indentation to group code, a bit like Python. Lines at the left margin are the
"top level" of the file. When code belongs inside something (a function, a loop, an if), you
indent it with spaces. Tabs are not allowed. You'll see this in action from the next lessons on.
When you press Run, the F# compiler first checks the whole file. If something is wrong you get
an error with a position (such as (3,9), meaning line 3, column 9) and an error code like
FS0001, and nothing runs. If it compiles, the code at the top level runs once, from the first line to the last. That
is why a program can be as short as one printfn: there is no required main function in a
single-file program.
Write a program that prints exactly these two lines:
The program reads no input.
Print a short launch report. Build the first line from three printf calls that print 3...,
2... and 1..., followed by printfn "Liftoff!". The second line uses one printfn with a
%s and a %d placeholder to print the rocket name Comet and the crew size 4.
Expected output:
printfn "Hello, World!"printf "Loading"
printf "..."
printfn "done" // Loading...doneprintfn "%s is %d years old" "F#" 21
printfn "Pi is about %.2f" 3.14159 // Pi is about 3.14// A whole-line comment
printfn "This runs" // a comment after code
(* A block comment
over two lines *)Hello, World!
I am learning F#.3...2...1...Liftoff!
Comet launched with 4 crew.