views:

553

answers:

3

I've read through a good chunk of Expert F# and am working on building an actual application. While debugging, I've grown accustomed to passing fsi commands like this to make things legible in the repl window:

fsi.AddPrinter(fun (x : myType) -> myType.ToString())

I would like to extend this to work with the printf formatter, so I could type e.g.

printf "%A" instanceOfMyType

and control the output for a custom type. The book implies that this can be done (p 93, "Generic structural formatting can be extended to work with any user-defined data types, a topic covered on the F# website"), but I have failed to find any references as to how to actually accomplish this. Does anyone know how? Is it even possible?

Edit:

I should have included a code sample, it's a record type that I'm dealing with, e.g.

type myType = 
    {a: int}        
    override m.ToString() = "hello"

let t = {a=5}
printfn "%A" t
printfn "%A" (box t)

both print statements yield:

{a = 5;}
+3  A: 

Hmm... I vaguely recall some changes to this, but I forget if they happened before or after the CTP (1.9.6.2).

In any case, on the CTP, I see that

type MyType() =
    override this.ToString() = "hi"
let x = new MyType()
let xs = Array.create 25 x
printfn "%A" x
printfn "%A" xs

when evaluated in the VFSI window does what I would want, and that

x;;
xs;;

also prints nicely. So, I guess I am unclear how this differs from what is desired?

Brian
Thanks; see my edit to the original post, it's a record type with a member function added, and behaves differently than a class type...
flatline
@Brian, yes, that should work, but as flatline says, it doesn't work with union and record types. I ran into this a while ago: http://cs.hubfs.net/forums/post/9163.aspx (can't remember if I sent something to fsbugs when I didn't get any followups, sorry)
Kurt Schelfthout
A: 

If you override ToString method, that should do.

Can Erten
+2  A: 

Imo, this is a bug in the ctp, but if you want to get it to work right now, the only way I know of is to override a deprecated interface, IFormattable. This allows you to control directly what is printed using structural formatting.

See also this thread on hubfs.

Like I said, expect this to change "soon". If you can do without, save yourself the hassle.

Kurt Schelfthout
Thanks, it looks like you ran into the same thing. I'll check out IFormattable, though it looks like I shouldn't depend on it being there in the future.
flatline