Home > Net >  In F# is it OK to make a shorthand function to print using %A
In F# is it OK to make a shorthand function to print using %A

Time:09-26

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?!

CodePudding user response:

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 takes ToString() behaviour). I often also make one specific for logging that behaves like printfn, 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.

  • Related