Python:
In [1]: [1,2][0:4]
Out[1]: [1, 2]
Julia:
julia> [1,2][1:5]
ERROR: BoundsError: attempt to access 2-element Vector{Int64} at index [1:5]
Why does Julia throw on overlong slice? Is this somehow useful for performance?
Python:
In [1]: [1,2][0:4]
Out[1]: [1, 2]
Julia:
julia> [1,2][1:5]
ERROR: BoundsError: attempt to access 2-element Vector{Int64} at index [1:5]
Why does Julia throw on overlong slice? Is this somehow useful for performance?
Yikes. Does that really work in python…?
It turns out to be nice to think of slicing as an intersection of indices. Under that interpretation, slicing outside the bounds of an array is a standard technique, rather than an error condition.
Python does it that way, as shown.
Ruby too
irb(main):002:0> [10,20][0,4]
=> [10, 20]
Haskell does it the same way:
Prelude> take 4 [1,2]
[1,2]
It’s also recommended by Prof. John Ousterhout in his “A Philosophy of Software Design”.
Atleast in my experience, this kind of thing leads to hard to find bugs in python, were something is initialized incorrectly but it fails silently instead of giving a bounds error.
This is similar to julia first()/last() functions instead of slicing. And they don’t throw either: first([1, 2], 4) == [1, 2].
Actually slicing a vector in haskell is also restricted to valid indices, same as in julia: e.g. Data.Vector.
That’s a good point about first
/last
. There’s also
julia> [1,2][5:end]
Int64[]
though not
julia> [1,2][begin:5]
ERROR: BoundsError: attempt to access 2-element Vector{Int64} at index [1:5]
That’s because [1,2][5:end]
is equivalent to
a = [1,2]
a[5:lastindex(a)]
which makes an empty range:
julia> a = [1,2]
2-element Vector{Int64}:
1
2
julia> 5:lastindex(a)
5:4
julia> ans |> isempty
true
If it’s clear that the result would be empty, not having it error seems sensible to me. In contrast to begin:5
, you’re never requesting data the array doesn’t have, since you’re not requesting any data at all.
I’ll note that we’ve famously taken very different viewpoints on programming language design issues from Dr Ousterhout, ie. Ousterhout’s dichotomy vs the two language problem. Doesn’t mean he’s wrong about anything in particular but his recommendation may not necessarily hold positive weight.