Julia built in function for sum of array?

16,303

As @Michael K. Borregaard mentions, you reasigned the variable sum (exported by default from Base) with the value of a Float64 at some point. When you restated your session, sum was again the Base.sum default, ie:

julia> x = rand(10)         
10-element Array{Float64,1}:
 0.661477                   
 0.275701                   
 0.799444                   
 0.997623                   
 0.731693                   
 0.557694                   
 0.833434                   
 0.90498                    
 0.589537                   
 0.382349        

julia> sum                                                    
sum (generic function with 16 methods)                        

julia> sum(x)               
6.733930084133119 

julia> @which sum(x)                                          
sum(a) in Base at reduce.jl:359     

Notice the warning:

julia> original_sum = sum
sum (generic function with 16 methods)

julia> sum = x[1]                                             
WARNING: imported binding for sum overwritten in module Main  
0.6614772171381087                                                

julia> sum(x)                                                 
ERROR: MethodError: objects of type Float64 are not callable  

julia> sum = original_sum
sum (generic function with 16 methods)

julia> sum(x)               
6.733930084133119  
Share:
16,303
Ben10
Author by

Ben10

Updated on June 05, 2022

Comments

  • Ben10
    Ben10 almost 2 years

    In Julia are there no built in functions to sum an array of numbers?

    x = rand(10)
    sum(x) # or sum(x, 1)
    
    ERROR: MethodError: objects of type Float64 are not callable
    

    I mean I could write a for loop to sum it as follows,

    sum = 0.0    
    for i in 1:length(x)
        sum += x[i]
    end
    

    but it just surprises me if julia don't have this built in somewhere?