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.
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 = Printf.kprintf (fun s -> let orig = System.Console.ForegroundColor System.Console.ForegroundColor <- c; System.Console.WriteLine(s) System.Console.ForegroundColor <- orig) fmt
cprintfn function takes
advantage of the
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: ...