Chapter 5. INPUT AND OUTPUT
In this chapter, we examine the various ways in which an F# program can transfer data, including printing to the screen and saving and loading information on disc. In particular, we examine some sophisticated tools for F# which greatly simplify the task of designing and implementing programs to load files in well-defined formats.
PRINTING
The ability to print information on the screen or into a string or file is useful as a means of conveying the result of a program (if the result is simple enough) and providing run-time information on the current state of the program as well as providing extra information to aid debugging. Naturally, F# provides several functions to print to the screen. In particular, the printf function can be used to print a variety of different types and perform some simple formatting.
The printf function understands several format specifiers:
%s print a
string%d print an
int% f print a
float%g print a
floatin scientific notation%a print a value using a custom print function
%0 print a value of any type using the
ToString() method.%A print a value of any type using the built-in structural pretty printer.
Special characters can also be printed:
\n newline
\" double-quotes
\t tab
For example, the following prints a string in quotes, an int and then a float:
> printf "String: \"%s\", int: %d, float: %f\n" "foo" 3
7.4;;
String: "foo", int: 3, float: 7.4The following function uses the generic %A format specifier to print a value as a running F# ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access