Learn/F#/1. Hello, output
Lesson 1 of 8
Sign in

F#, lesson 1

Hello, output

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.

Printing without a new line

printf (no n) prints and stays on the same line. The next print continues right after it:

Placeholders

The first argument of printf and printfn is a format string. It can contain placeholders that are filled with the values that follow:

PlaceholderType

2 exercises to try what you just read.

Exercise 1

Your first program

Press Ctrl Enter or Check to test your code.

Exercise 2

Launch report

Press Ctrl Enter or Check to test your code.

%sstring
%dinteger
%ffloating-point number (%.2f for 2 decimals)
%btrue / false
%Aany 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.

Comments

// starts a comment that runs to the end of the line. (* ... *) is a block comment that can span several lines.

Indentation matters

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.

How a program runs

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.

Further reading

  • Tour of F#
  • Plain text formatting (printf)

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...done
printfn "%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.