If this were Facebook, I would "Like" this :)
On Wednesday, September 23, 2015 at 9:34:27 AM UTC+8, Tim Holy wrote: > > At the risk of encouraging emacs users to "fix" the syntax with ctrl-T, > I'd > propose the following (apparently complete?) solution: > > > immutable FormatString{S} end > > FormatString(str::AbstractString) = FormatString{symbol(str)} > > macro f_str(arg) > :(FormatString{symbol($arg)}) > end > > @generated function Base.print{format}(::Type{FormatString{format}}, > args...) > meta = Expr(:meta, :inline) > fmt = string(format) > allargs = [:(args[$d]) for d = 1:length(args)] > quote > @printf($fmt, $(allargs...)) > end > end > > > > Demo: > julia> print(f"%.3f", pi) > 3.142 > julia> function foo(strs) > for str in strs > print(FormatString(str), pi) > end > end > foo (generic function with 1 method) > > julia> strs = ("%.3f\n", "%.5f\n") > ("%.3f\n","%.5f\n") > > julia> foo(strs) > 3.142 > 3.14159 > > julia> @time 1 # just to warm up @time > 0.000004 seconds (148 allocations: 10.151 KB) > 1 > > julia> @time foo(strs) > 3.142 > 3.14159 > 0.000106 seconds (18 allocations: 704 bytes) > > > Nice that we get to re-use the macro that Stefan worked so hard on! > > Best, > --Tim >