Why throw on overlong slice?

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…?

1 Like

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”.

1 Like

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.

5 Likes

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.

3 Likes

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]
1 Like

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.

4 Likes

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.

8 Likes