F# Printfn Examples: printf, FormatsWrite values to the screen with the printfn and printf methods. See format codes for strings and ints.
Printfn.A program executes. But it never tells us the values of its variables. Instead we must use printfn to have it report this information. This method is often used.
Format codes.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.
First example.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."
Next: We use the "%A" code, which inserts any value. It does not require a specific type of argument.
String: We can use some surrounding text in our printfn statement. The variable is inserted into this string.
|F# program that uses printfn 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" id Output 10 10 The ID is 10. 20|
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.Listdict
|F# program that uses printfn with list, dict 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 Output [10; 20; 30] [("cat", 10); ("frog", 40); ("rat", 100)]|
Printf, no newlines.This 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.
|F# program that uses printf, no newlines 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... " v Output parrot... finch... bluebird...|
Sprintf.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.
|F# program that uses sprintf // Call sprintf to write values to a string. let result = sprintf "Result: %A, %A" 10 20 // Now print our string. printfn "%A" result Output "Result: 10, 20"|
Parenthesis.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).
A review.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.
Dot Net Perls
|© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, firstname.lastname@example.org.|