Cover by Chris Smith

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 =
    Printf.kprintf
        (fun s ->
            let orig = System.Console.ForegroundColor
            System.Console.ForegroundColor <- c;
            System.Console.WriteLine(s)
            System.Console.ForegroundColor <- orig)
        fmt

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required