In F# we often write values to the console. We use printfn
with multiple arguments to print values—a format string
is required. String
interpolation syntax is also available.
The first argument to printfn
or printf
must be a format string
. The second argument (a value) is inserted in it and written. Printfn has a trailing newline. Printf
does not.
This program uses printfn
with various format codes. We introduce a mutable id variable. We print it as an integer (numeric) value with the code "%d."
printfn
statement. The variable is inserted into this string
.let mutable id = 10 // Print the variable as an int. printfn "%d" id // Print it as a value. printfn "%A" id // Use some surrounding text. printfn "The ID is %A." id // Modify the id variable and print it again. id <- 20 printfn "%A" id10 10 The ID is 10. 20
String
interpolationIn modern F# programs the string
interpolation syntax may be the best choice for printing values. We use it with printfn
and the "$" character.
let value = "bird" // Use string interpolation to display the value. printfn $"The value: {value}" printfn $"The value uppercase: {value.ToUpper()}"The value: bird The value uppercase: BIRD
List
, dict
With the "%A" code we can print entire lists or dicts in a single statement. No for-in
loop is needed to write all the elements. This makes programs easier to develop.
let codes = [10; 20; 30] let data = ["cat", 10; "frog", 40; "rat", 100] // Use printfn on list and dict types. // ... All included values are printed to the console. printfn "%A" codes printfn "%A" data[10; 20; 30] [("cat", 10); ("frog", 40); ("rat", 100)]
Printf
, no newlinesThis method does not add a trailing newline. So we can use it to write multiple values to a single line in a for-in
loop. We print values as strings with the "%s" code.
let values = ["parrot"; "finch"; "bluebird"] // Use printf on values in a list. // ... No newline is inserted after the values. for v in values do printf "%s... " vparrot... finch... bluebird...
Sometimes we do not want to write to the console. With sprintf we can insert values into a string
, and use that elsewhere in the program.
// Call sprintf to write values to a string. let result = sprintf "Result: %A, %A" 10 20 // Now print our string. printfn "%A" result"Result: 10, 20"
When calling a method in a printfn
statement, we need to surround it with parentheses. This treats the method as something to be evaluated (a value).
With printfn
and printf
, we write values to the screen (the console). This helps us develop small and readable F# programs. Format codes help simplify the output.