Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an F# structured printf bug?

Tags:

.net

printf

f#

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

like image 217
controlflow Avatar asked May 23 '10 12:05

controlflow


1 Answers

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 
like image 78
Tomas Petricek Avatar answered Oct 21 '22 19:10

Tomas Petricek