Interactive Session #2: printing

Printing in F# is very similar to the famous printf function in C/C++.

> printf "Hello World\n";;
Hello World
val it : unit = ()

(* Alternatively printfn appends a newline automatically *) ;;

> printfn "Hello again";;
Hello again
val it : unit = ()

How many times have you mismatched the printf format string and the actual arguments? F# can infer and check the type of arguments passed to printf.

> printfn "result = %d" "1";;

 printfn "result = %d" "1";;
 ----------------------^^^^^

~/stdin(33,23): error FS0001: The type 'string' is not
compatible with any of the types byte,int16,int32,int64,sbyte,
uint16,uint32,uint64,nativeint,unativeint, arising from the use of
a printf-style format string
> printfn "result = %d" 1;;
result = 1
val it : unit = ()

printf in F# is very handy for debugging, as it is capable of printing any type, even complex tuples, lists and trees with the ‘%A’ format specifier.

> printfn "%A" [1; 2; 3; 4];;
[1; 2; 3; 4]
val it : unit = ()

> printfn "%A" ("Joe", "Smith", 35, [6.50; 6.20; 6.70]);;
("Joe", "Smith", 35, [6.5; 6.2; 6.7])
val it : unit = ()

More can be found here Core Printf Module (F#).

Advertisements
This entry was posted in Getting Started. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s