Numbers as single-element collections

Hi, I was reading base/number.jl, and I was wondering about the rationale of

start(x::Number) = false
next(x::Number, state) = (x, true)
done(x::Number, state) = state
isempty(x::Number) = false
in(x::Number, y::Number) = x == y

which makes numbers single-element collections.

  1. Where could I learn more about the rationale?
  2. Why restrict to numbers?
2 Likes

There has been some discussion at https://github.com/JuliaLang/julia/pull/19700 and issues linked in it.

Basically, it’s often convenient to consider scalar numbers to be immutable zero-dimensional arrays containing only themselves. In fact, Matlab doesn’t distinguish between scalars, single-element vectors or single-element matrices, at all – they’re all represented as 1×1 matrices. However, that can occasionally cause hard-to-spot bugs, the most common being writing for i = n when one means for i = 1:n.

R does the same (has no scalars). IMO for Julia, it is one of those DWIM constructs that look nice initially, but are more trouble than what they are worth. AFAIK it is not documented (at least in ?in), and then it special-cases numbers.

Anyway, it is not a big deal, and maybe when I read more code in Base I will understand the reasons (or submit a PR :wink:)

I’ve been pushing for the removal of this feature since 2010, so believe me, the discussion has been had. The trouble is that every time someone tries to do it, it turns out to be surprisingly painful – there’s a remarkably large amount of code even in the standard library that seems to rely on this feature. A PR to remove it would be welcomed, however.

3 Likes

The new broadcast semantic for v0.6 (scalar by default) should help, and removing these methods would be consistent with that.

Agreed that it’s tons of work, though.