Why is length of integers = 1?

#1

Is there any reason to have length of integers equal to 1?

For example, length(100) = 1. Recently, I had a bug in my code because of this. Shouldn’t length(a_number) result in an error?

0 Likes

#2

Numbers are iterable objects to enable code like the following to just work with integer inputs:

function triplesum(v)
    s = zero(eltype(v))
    for element in v
        s += 3*element
    end
    return s
end

julia> triplesum(1:5)
45

julia> triplesum(1)
3

The length of an iterable is the number of iterations performed to traverse each element (which for a number, as you found, is one).

2 Likes

#3

Enjoy the read :slight_smile:

3 Likes

#4

Thank you. Will read the linked issue.

0 Likes