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.
e.g.
- printfn "Hello %s" "World"
- 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:
- With override of ToString() method
- Using a custom callback with ‘%a’ specifier which allows a callback function that take TextWriter as argument.
With option 1:
-
- let yymmdd1 (date:System.DateTime) = date.ToString("MM/dd/YYYY")
-
- [<EntryPoint>]
- let main argv =
- printfn "using ToString = %s" (yymmdd1 System.DateTime.Now)
- System.Console.ReadKey() |> ignore
- 0
With option 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.
- printfn "unescaped: %"
- printfn "escape: %%"
Read out more about F# print formatters
here.
Read more articles on F#: