Description
One way to handle the replacing @printf
may be to enhance string interpolation. To do this, one could introduce a to_str
function (I am not set on the name, but am using it for discussion. This is a proposal for the architecture). For example, currently ”piece1$var piece2”
parses similarly to string(“piece1", var, “ piece2”)
. In reality, "$var"
is the same as "$(var)"
. My idea is to extend the interpolating $()
to a full function call, to_str
, and allow arguments.
For example, we could instead use ”piece1$(var,args...) piece2”
which would extend to string(“piece1", to_str(var,args...), “ piece2”)
. to_str
would be a function which returns a String (or if not, to_str
is reursively called on the output). The standard to_str
would be
to_str(x::Any) = string(x)
which would just give the string output of the print
method. But this let's us generalize a lot. For example, we could do
to_str(x::AbstractFloat,style::Symbol;dec=2) = ...
to be a function which gives back a string which which is in the chosen style. This would allow one to make $(var,:sci,dec=3) is the result"
interpolate into the string var
in scientific notation with 3 decimal places.
I am not proposing the exact details for the Base to_str
functions, but I think this architecture would work really well for Base since it would cover most use cases while being very extendable (anyone could add dispatches for their own types, so they would work seamlessly for interpolation). This is very different from the idea of #10610, but I think this is a conservative extension to current interpolation behavior that matches well with Julia intuition and could cover most of what people need with @printf
(with anything super special handled in packages).