Compat usage


#1

How do I use Compat.jl to get this julia-0.7 code running on 0.6 as well? (the code’s from the Julia Microbenchmarks)

function parseintperf(t)
    local n, m
    for i=1:t
        n = rand(UInt32)
        s = string(n, base = 16)                # was s = hex(n) in 0.6
        m = UInt32(parse(Int64, s, base = 16))  # was m = UInt32(parse(Int64, s, 16)) in 0.6
        @assert m == n
    end
    return n
end

Prefacing the key lines with @compat as suggested by the Compat.jl README doesn’t work. There doesn’t seem to be anything relevant in the README’s list of special cases, either.

using Compat
import Compat.String

function parseintperf(t)
    local n, m
    for i=1:t
        n = rand(UInt32)
        @compat s = string(n, base = 16)
        @compat m = UInt32(parse(Int64, s, base = 16))
        @assert m == n
    end
    return n
end

This runs fine under 0.7 but not under 0.6.

julia> include("parseintperf.jl")
parseintperf (generic function with 1 method)

julia> parseintperf(100)
ERROR: function string does not accept keyword arguments
Stacktrace:
 [1] kwfunc(::Any) at ./boot.jl:237
 [2] parseintperf(::Int64) at /home/gibson/scratch/julia/parseintperf.jl:8

julia> versioninfo()
Julia Version 0.6.3
Commit d55cadc350 (2018-05-28 20:20 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Core(TM) i5-6300U CPU @ 2.40GHz
  WORD_SIZE: 64
  BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell)
  LAPACK: libopenblas64_
  LIBM: libopenlibm
  LLVM: libLLVM-3.9.1 (ORCJIT, skylake)

I could use a working example of Compat usage.


#2

Answer, from @ararslan and @ChrisRackauckas on https://julialang.slack.com: The correct syntax is

using Compat
using Compat: string, parse

function parseintperf(t)
    local n, m
    for i=1:t
        n = rand(UInt32)
        @compat s = string(n, base = 16)
        @compat m = UInt32(parse(Int64, s, base = 16))
        @assert m == n
    end
    return n
end

However this doesn’t work because Compat doesn’t have the 0.7-style string with keyword arguments. So instead do this

function parseintperf(t)
    local n, m

    for i=1:t
        n = rand(UInt32)
        @static if VERSION >= v"0.7.0-DEV.4446"
            s = string(n, base = 16)
            m = UInt32(parse(Int64, s, base = 16))
        else
            s = hex(n)
            m = UInt32(parse(Int64, s, 16))
        end
        @assert m == n
    end
    return n
end

You can also do this more slickly by defining function closures like _hex(n) = string(n, base=16) inside an if VERSION statement prior to the for loop, but this has a little overhead I don’t want in the benchmarks.