Printing and formatting outputs in F#

In this post we’ll discuss the very basic function that everyone uses in any language. When someone starts learning programming language very first thing they want to do is printing/writing out on console.

The Print

(image courtesy

F# have two basic function “printf” and “printfn” to print out the information on console.

// The printf/printfn functions are similar to the

// Console.Write/WriteLine functions in C#.


printfn "Hello %s" "World"
printfn "it's %d" 2016

The print function in F# are statically type checked equivalent to C-style printing. So any argument will be type checked with format specifiers. Below is list if F# format specifiers.

·         %s for strings

·         %b for bools

·         %i or %d for signed ints%u for unsigned ints

·         %f for floats

·         %A for pretty-printing tuples, records and union types, BigInteger and all complex types

·         %O for other objects, using ToString()

·         %x and %X for lowercase and uppercase hex

·         %o for octal

·         %f for floats standard format

·         %e or %E for exponential format

·         %g or %G for the more compact of f and e.

·         %M for decimals

Padded formatting

·         %0i pads with zeros

·         %+i shows a plus sign

·         % i shows a blank in place of a plus sign

Date Formatting

There’s not built-in format specifier for date type. There are two options to format dates:

1. With override of ToString() method

2. Using a custom callback with ‘%a’ specifier which allows a callback function that take TextWriter as argument.

With option 1

// function to format a date
let yymmdd1 (date:System.DateTime) = date.ToString("MM/dd/YYYY")
let main argv = 
    printfn "using ToString = %s" (yymmdd1 System.DateTime.Now)
    System.Console.ReadKey() |> ignore // To hold the console window
    0 // return an integer exit code

With option 2

// function to format a date onto a TextWriter
let yymmdd2 (tw:System.IO.TextWriter) (date:DateTime) = tw.Write("{0:yy.MM.dd}", date)
printfn "using a callback = %a" yymmdd2 System.DateTime.Now

Ofcourse here option 1 is much easier but you can go with any of the option.

Note - Printing ‘%’ character would required to be escaped as it has special meaning.

printfn "unescaped: %" // error
printfn "escape: %%"

Read out more about F# print format specifiers here.

No comments:

Post a Comment