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 the very first thing they want to do is printing/writing out on console.

The Print

F# has two basic functions; “printf” and “printfn” to print out the information on console.

  1. // Theprintf/printfn functions are similar to the  
  2. // Console.Write/WriteLine functions in C#.  
e.g.
  1. printfn "Hello %s" "World"  
  2. printfn "it's %d" 2016  
Formatting specifiers’ cheatsheet

The print functions in F# are statically type checked equivalent to C-style printing. So any argument will be type checked with format specifiers. Below is list of 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:

  1. // function to format a date  
  2. let yymmdd1 (date:System.DateTime) = date.ToString("MM/dd/YYYY")  
  3.   
  4. [<EntryPoint>]  
  5. let main argv =   
  6. printfn "using ToString = %s" (yymmdd1 System.DateTime.Now)  
  7. System.Console.ReadKey() |> ignore// To hold the console window  
  8. // return an integer exit code 
With option 2:
  1. // function to format a date onto a TextWriter  
  2. let yymmdd2 (tw:System.IO.TextWriter) (date:DateTime) = tw.Write("{0:yy.MM.dd}", date)  
printfn "using a callback = %a" yymmdd2 System.DateTime.Now
Of course here option 1 is much easier but you can go with any of the options.

Note: Printing ‘%’ character will require escaping as it has special meaning.
  1. printfn "unescaped: %" // error  
  2. printfn "escape: %%"   
Read out more about F# print formatters here.
 
Read more articles on F#:

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now