tags:

views:

134

answers:

2

Code:

printfn "%10s"  "abc"
printfn "%-10s" "abc"
printfn "%10d"   123
printfn "%-10d"  123
printfn "%10c"   'a'
printfn "%-10c"  'a'

Output:

       abc
abc
       123
123
a
a

So right aligning %c does not work as I expect...

F# 2.0 build 4.0.30319.1

+3  A: 

%c isn't listed in the table of valid types for F# printf. Maybe that's the cause of your problem.

Quite strange, according to the table there isn't a type to print single characters at all.

David Klein
+5  A: 

I don't think that the fact that it is missing in the table of valid types is causing the issue (the "%c" modifier is definitely supported, because the type of printfn "%c" is char -> unit as you would expect). So, it does look like a bug to me.

An easy workaround is to use the "%O" modifier which takes any type (also including char values) and formats it using ToString method (avaliable for all .NET types):

> printfn "%10O" 'a';;
         a
val it : unit

BTW: I looked at the F# library source code (from the CTP release) and here is the relevant bit from printf.fs (line 478):

| 's',nobj::args -> 
  formatString outputChar info width (unbox nobj) false; i+1,args
| 'c',nobj::args -> 
  outputChar (unbox nobj); i+1,args // (1)
| 'b',nobj::args -> 
  formatString outputChar info width 
    (if (unbox nobj) then "true" else "false") false; i+1,args
| 'O',xobj::args -> 
  formatString outputChar info width 
    (match xobj with null -> "<null>" | _ -> xobj.ToString()) false; i+1,args

The line (1) formats a character and it ignores the width parameter (which is the width you specified). So, unless this is (for some reason, e.g. performance?) intended behavior, it really feels looks a bug!

I suppose that the following implementation would fix the problem (Brian ;-)! Are you there?):

| 'c', nobj::args -> 
  formatString outputChar info width 
    (string ((unbox nobj):char)) false; i+1,args 
Tomas Petricek