Udostępnij za pośrednictwem


F# Zen - Colored printf

It’s easy to lose track of important data when logging output to the console window, fortunately you can use the System.Console.ConsoleColor property to set the output color. But unlike F#’s printfn, System.Console.WriteLine doesn’t use type inference and feels much different than the printf and printfn methods you’re used to.

Here’s how to create a version of printfn that takes a console color parameter.

 #light

/// Colored printf
let cprintf c fmt = 

    Printf.kprintf 
        (fun s -> 
            let old = System.Console.ForegroundColor 
            try 
              System.Console.ForegroundColor <- c;
              System.Console.Write s
            finally
              System.Console.ForegroundColor <- old) 
        fmt
        
// Colored printfn
let cprintfn c fmt = 
    cprintf c fmt
    printfn ""

open System
cprintfn ConsoleColor.Blue  "Hello, World in BLUE!"
cprintfn ConsoleColor.Red   "... and in RED!"
cprintfn ConsoleColor.Green "... and in GREEN!"

let rotatingColors = 
    seq { 
        let i = ref 0
        let possibleColors = Enum.GetValues(typeof<ConsoleColor>)
        while true do
            yield (enum (!i) : ConsoleColor)
            i := (!i + 1) % possibleColors.Length
    }

"Experience the rainbow of possibility!"
|> Seq.zip rotatingColors
|> Seq.iter (fun (color, letter) -> cprintf color "%c" letter)

printfn ""
Console.WriteLine("(press any key to continue")
Console.ReadKey(true) |> ignore

Comments