Hello,

I made a trivial change to a some clever code by Tim Holy, and used it to 
make printf() and sprintf() function with the familiar syntax that we know 
from C/C++ (requires Julia 0.4):


immutable FormatString{S} end

FormatString(str::AbstractString) = FormatString{symbol(str)}

@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
@generated function Base.sprint{format}(::Type{FormatString{format}}, 
args...)
    meta = Expr(:meta, :inline)
    fmt = string(format)
    allargs = [:(args[$d]) for d = 1:length(args)]
    quote
        @sprintf($fmt, $(allargs...))
    end
end

function printf(s::AbstractString, args...)
    print(FormatString(s), args...)
end
function sprintf(s::AbstractString, args...)
    print(FormatString(s), args...)
end


Could (or should) something like this be included in Julia by default? The 
first time you call printf() sprintf() with a new format string, the 
function call is slower than the @printf and @sprintf macros, but 
subsequent calls are just as fast:

julia> @time @printf("%7d  %7.2f", 220/7, 22/7)
     31     3.14  0.024334 seconds (20.68 k allocations: 912.738 KB)

julia> @time @printf("%7d  %7.2f", 220/7, 22/7)
     31     3.14  0.000102 seconds (30 allocations: 1.094 KB)

julia> 

julia> fmt = "%6d  %7.2f"
"%6d  %7.2f"

julia> @time printf(fmt, 220/7, 22/7)
    31     3.14  0.036154 seconds (36.81 k allocations: 1.675 MB)

julia> @time printf(fmt, 220/7, 22/7)
    31     3.14  0.000095 seconds (37 allocations: 1.250 KB)



Daniel.

Reply via email to