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 float in 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.4

The following function uses the generic %A format specifier to print a value as a running F# ...

Get F# for Scientists now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.