Warning: Method definition. Simple explanation please

first-steps

#1

Hi,

I’m totally new to Julia, and I was hoping for a simple explanation of the error in the title of this post. Other posts I’ve read say something about conditionally defining functions. But I’m encountering this error in a simple loop:

function sum(x)
	z = 0
	for i = 1:x
		z = z + 1
	end
	return z
end

sum(10)

(obviously a illustrative example)
I think it has something to do with the fact that the variable z is defined and modified in the function.

I’d like to know exactly what the problem is here and how I can avoid it. May be something very simple, but still very confusing for a beginner.

Thanks


#2

Can you post the output of running that in your REPL along with the full error message please? This works correctly on my system (as it should).


#3

Sure, the output is below:

julia> include(“test.jl”)
WARNING: Method definition sum(Any) in module Main at C:\users\sam2\desktop\collatz project\code\test.jl:3 overwritten at C:\users\sam2\desktop\collatz project\code\test.jl:3.
10

I assume that the 3 in the otput refers to line 3, which is z = 0.


#4

EDIT: It just means that you are overwriting the method definition (a method is a function with a given combination of input argument types). You have already defined the sum(Any) method once, you now define it again (I assume you ran the code twice?). The warning is just a heads up that you are redefining the function, so you don’t do it unintentionally. It is useful because defining functions with different methods (combinations of arguments) is common in Julia, but when doing that, you may accidentallly define a new method that overwrites a previously written one. Line 3 is probably the line function sum(x).

In this case, you can ignore the warning. You will always expect method definition warnings when including a file with functions more than once.


#5

Ok, that makes sense. Thanks for that.

Yes, if I restart Julia, then the message does not appear the first time I run the code, but it does appear the second and subsequent times.

I’m using notepad++ and line 3 is z=0 in there, but I guess Julia may count the lines differently.

Thanks again.


#6

Take Juno for a spin instead http://junolab.org/ That’s the best IDE for julia (I am sure there are people who prefer emacs or vim or something).