You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
O'Reilly logo

F# Script Recipes

This section will highlight some simple utilities that can help make your F# scripts more effective—such as taking advantage of console coloring or automating data input to Microsoft Excel.

Colorful Output

Scripts don’t primarily invest in a UI, rather they are designed not to need any user input. However, taking advantage of a color console can dramatically improve the readability of your script’s output. Example 9-4 defines a cprintfn function that behaves just like printfn, taking a string filled with format specifiers and additional arguments, except that it also takes a color parameter.

Example 9-4. Producing colorful output

/// Colorful printing for helpful diagnostics
let cprintfn c fmt =
        (fun s ->
            let orig = System.Console.ForegroundColor
            System.Console.ForegroundColor <- c;
            System.Console.ForegroundColor <- orig)

The cprintfn function takes advantage of the Printf.kprintf function in the F# library, which does all the conversion of the format string, such as "%d %f %s", and the additional arguments, and calls the provided function once they have been combined into the final result. The cprintfn function then simply updates the console color before doing the actual printing.

The following code prints text to the console in various colors. The last section of the code uses a little functional programming magic to print a string where each letter is in a different color—see if you can figure out how it works (hint: ...

The best content for your career. Discover unlimited learning on demand for around $1/day.