Santosh Kumar R
Santosh Kumar R

Reputation: 31

Any efficient way of using Julia in Jupyter without restarting the kernel for redefining variables/functions?

So I have been trying to adapt my python codes to Julia instead of fortran mainly because of the fact I have Jupiter to easily test my work on the fly. But in Julia 1, I am unable to find any easy way to redefine a already defined function in another cell to test it out. For instance

function a(b);return b+4;end

and then in next cell I would like to test instead loose the condition and have it something like

function a(b,c);return b+c;end

But I do not want to change the name because I have other dependent functions in which I call a. The reason to do this is for prototyping the best possible way to define a and obviously this wouldn't be a part of the main code.

Any way how to do this ?

Upvotes: 3

Views: 443

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

Julia uses multiple dispatch and these are two different functions (or more exactly two different methods of the same function). Hence, no change of name is needed.

julia> function a(b);return b+4;end
a (generic function with 1 method)

julia> function a(b,c);return b+c;end
a (generic function with 2 methods)

julia> methods(a)
# 2 methods for generic function "a":
[1] a(b) in Main at REPL[1]:1
[2] a(b, c) in Main at REPL[2]:1

Basically, rerunning a Jupyter cell will redefine the function (if it is the same set of parameter types) so there is no problem here.

More complicated situation is when you want to change a type of a constants because they go deeper into compiler. Constants cannot change their type.
Functions are constants. Hence, if you try to assign a non-function type it will trow an error.

julia> typeof(a) <: Function
true

julia> a = 5
ERROR: invalid redefinition of constant a
Stacktrace:
 [1] top-level scope at REPL[9]:1

Upvotes: 1

Related Questions