Is this string2range function correct?

I wrote the following function:

function string2range(string_range)
    a, b, c = split(string_range, ':')
    a1 = parse(Float64, a)
    b1 = parse(Float64, b)
    c1 = parse(Float64, c)
    StepRangeLen(a1, b1, 1+Int64(round((c1-a1)/b1)))
 end

Usage:

julia> string2range("1:0.5:5")
1.0:0.5:5.0

I use it to parse ranges defined in configuration files.

But is it implemented correctly?

I might try

julia> s = "1:0.5:5"
"1:0.5:5"

julia> p = Meta.parse(s)
:(1:0.5:5)

julia> (p.args[1] == :(:) || error("not a range")); (:)(p.args[2:end]...)
1.0:0.5:5.0
4 Likes

What is (:) doing?

It makes the range

julia> (:)(1,.5, 2) == 1:.5:2
true
1 Like

here you can find @sijo’s detailed answer to a similar question

Linking related post and solution.

2 Likes