Skip to content

Instantly share code, notes, and snippets.

@carlobaldassi
Created June 14, 2013 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlobaldassi/5778713 to your computer and use it in GitHub Desktop.
Save carlobaldassi/5778713 to your computer and use it in GitHub Desktop.
Quick hack to define gnuplot's-like ranges in Julia
module GPRangeTst
import Base: colon, show
export autoscale, parse_gpr
immutable AutoScale
end
autoscale = AutoScale()
immutable GPRange
auto::Bool
lb::Union(Real, Nothing, GPRange)
ub::Union(Real, Nothing, GPRange)
function GPRange(a::Bool, lb, ub)
if a && (isa(lb, GPRange) || isa(ub, GPRange))
error("invalid GPRange")
end
if !a && (lb == nothing || ub == nothing)
error("invalid GPRange")
end
new(a, lb, ub)
end
end
function GPRange(gpr::GPRange)
if gpr.auto && isa(gpr.lb, Real) && isa(gpr.ub, Real)
error("Invalid GPRange")
end
gpr
end
GPRange(r::Range1) = GPRange(false, first(r), last(r))
GPRange(a::AutoScale) = GPRange(true, nothing, nothing)
colon(lb::Real, a::AutoScale, ub::Real) = GPRange(true, lb, ub)
colon(lb::Real, a::AutoScale) = GPRange(true, lb, nothing)
colon(a::AutoScale, ub::Real) = GPRange(true, nothing, ub)
colon(lb::GPRange, ub::GPRange) = GPRange(false, lb, ub)
colon(lb::GPRange, ub::Real) = GPRange(false, lb, ub)
colon(lb::Real, ub::GPRange) = GPRange(false, lb, ub)
show_gpb(io::IO, b::Nothing) = print(io, "*")
show_gpb(io::IO, b::Real) = print(io, b)
function show_gpb(io, b::GPRange)
@assert b.auto == true
if b.lb != nothing
print(io, "$(b.lb)<")
end
print(io, "*")
if b.ub != nothing
print(io, "<$(b.ub)")
end
end
function show(io::IO, gpr::GPRange)
print(io, "[")
show_gpb(io, gpr.lb)
print(io, ":")
show_gpb(io, gpr.ub)
print(io, "]")
end
parse_gpr(x) = GPRange(x)
end
julia> include("gprangetst.jl")
julia> using GPRangeTst
julia> parse_gpr((1:autoscale):(autoscale:3))
[1<*:*<3]
julia> parse_gpr((1:autoscale):3)
[1<*:3]
julia> parse_gpr(1:3)
[1:3]
julia> parse_gpr(1:autoscale:2) # must fail
ERROR: Invalid GPRange
in GPRange at /home/carlo/gprange.jl:29
in parse_gpr at /home/carlo/gprange.jl:65
julia> parse_gpr(1:(autoscale:2))
[1:*<2]
julia> parse_gpr(autoscale)
[*:*]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment