I’m just starting to use F# for the first time, using VSCode and interactive notebooks. I am super annoyed at having to constantly write out
printfn "%A" something
because it kills me inside.
Is it wrong to at the start of every file simply write:
let print(something) = printfn "%A" something
// then use with
print(4 + 3) // int
print(3.7 + 1.1) //float
print("this is so much better") // text
Why the heck isn’t this built in?!
2
Answers
It turned out to be non trivial to make this built-in. Not because it’s a technical challenge, but because there’s not a single answer to “how to print X”, when the type is generic. Should it use internationalisation or not? Should it work like
ToString
? Should it behave like%A
, which is slow and has changed between F# versions?An implementation was made, and then halted, precisely because we didn’t have a definitive answer to these questions. I have an opinion and a preference, but my preference may not be yours. Which is why this isn’t as trivial as we’d like it to be.
That said, it is very common to have a little helper function like you wrote. Perhaps you’d make another one with
%O
(which takesToString()
behaviour). I often also make one specific for logging that behaves likeprintfn
, but logs it somewhere.The presence of interpolated strings has made the requirement for such helpers a little less demanding. But sure enough, functions that just dump the contents of a type are still very common.
Yes, of course, it’s ok to do this. Perhaps the easiest is to
And then use