The idiomatic way to specify a range from a
to b
inclusive is a:b
. Is there an standard operator or idiom to express the range a
to b
in which b
itself is excluded (something like range()
in Python)? I’m planning to make some updates to the token system for sorted containers in DataStructures.jl that will introduce notation for exclusive ranges. I prefer to follow an idiom if one exists.
a:b-1
? Seems easy enough to parse and reads nicely as from a to b minus one.
This would be a great solution if I had time to implement and test performant operations +(::Token,::Int)
and -(::Token,::Int)
, but unfortunately, that is outside the scope of work I could hope to accomplish in January. If there is an idiomatic notation that addresses just this limited usage, that would be great. If not, I will make something up.
You could also go crazy and do something like:
julia> a↦b = a:b-1
↦ (generic function with 1 method)
julia> collect(1↦4)
3-element Array{Int64,1}:
1
2
3
However, array comprehension fails for some reason:
julia> [i for i in 1↦4]
syntax: expected "]"
Stacktrace:
[1] top-level scope at In[12]:1
[2] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1091
@tamasgal, what about:
a↦b = (a:b-1)
This does not work, as explained by @mbauman. But the similar function does not look too bad:
julia> ↦(a,b) = a:b-1
↦ (generic function with 1 method)
julia> [i for i in ↦(1,4)]
3-element Array{Int64,1}:
1
2
3
The trouble with that comprehension is that ↦
has a very low precedence. The fix is [i for i in (1↦4)]
. You’ll generally need to add parens in places where you wouldn’t need to with :
. There aren’t many other operators with the same precedence as :
— IntervalSets uses ..
, but it’s also inclusive by default.
That said, intervals are perhaps the right mental model for the sort of operation I’m guessing you’re doing — and IntervalSets does have support for open intervals (it’s just the function OpenInterval
or explicit Interval{:closed,:open}
).
You could also add shorthands with one of these unicode operators which have the same precedence as :
and ..
— … ⁝ ⋮ ⋱ ⋰ ⋯
— but unfortunately none of them are very evocative of a half-open-on-one-side sort of thing.