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.

Padded formatting

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. [<EntryPoint>]
  4. let main argv =
  5. printfn "using ToString = %s" (yymmdd1 System.DateTime.Now)
  6. System.Console.ReadKey() |> ignore// To hold the console window
  7. 0 // 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#: