Sato
Sato

Reputation: 1133

Summing all elements of a 1-dimensional array in Julia

It is quite a basic question, but I couldn't find a question related to this issue. Suppose there is an array of type Array{Int64,1}, and I want to sum all elements in the array. The syntax I found online is simply to use the function sum on the array, like the following:

sum([i for i in 1:999 if i%3==0 || i%5==0])

However I received an error message

MethodError: objects of type Int64 are not callable

The message also appears when I try the syntax in the stackoverflow posts asking for summing multi-dimensional array. So what's the issue here?

Upvotes: 1

Views: 397

Answers (1)

DNF
DNF

Reputation: 12654

It works for me:

julia> sum([i for i in 1:999 if i%3==0 || i%5==0])
233168

Try to restart Julia. It is possible that you have used sum as a variable previously, and now the compiler doesn't recognize it as a function.

Also, it's better to avoid the allocations. It's not necessary to create an array, just use a generator instead:

julia> sum(i for i in 1:999 if i%3==0 || i%5==0)
233168

The latter is more than twice as fast for me, and zero allocations.

Upvotes: 6

Related Questions