let us suppose that we have:
include("file2.jl")
struct f1
function f1():
expressions
function f2(a,b,c):
return g2(a)
end
end
end
where g2()
is a nested function in a function called g1()
but in another file called file2
like this:
function g1()
function g2(b)
return expression
end
end
, how can i call f2
i have tried this:
a=f1()
a.f2(x,y,z)
but i got an ERROR: UndefVarError: g2 not defined
Function g1
in file2
returns a function object. To use it you have to call g1()
in your function f1
or f2
include("file2.jl")
struct f1
function f1()
# expressions
ftc = g1()
function f2(a,b,c)
return ftc(a)
end
end
end
or
include("file2.jl")
struct f1
function f1()
# expressions
function f2(a,b,c)
ftc = g1()
return ftc(a)
end
end
end
Then you can write:
a = f1() # calls the constructor returning the a callable object
a(3, 2, 1)
(Drop the colons in your function definitions In general it is easier to answer questions if you post real code instead of pseudo-code.
1 Like
i forgot to drop the colons because i’m coming from a Python background
but your idea is working
Ja, your approach looks object oriented. That made me wonder, how to define a method as an element of an object with access to other elements. Here is one way to achieve this:
mutable struct Omf
f
p::Int
function Omf(p)
omf = new()
omf.p = p
function fd(x)
return omf.p * x
end
omf.f = fd
return omf
end
end
julia> omf = Omf(1)
Omf(var"#fd#3"{Omf}(Omf(#= circular reference @-2 =#)), 1)
julia> omf.f(5)
5
julia> omf.p = 2
2
julia> omf.f(5)
10
julia> omf.p = 3
3
julia> omf.f(5)
15
However, I think programming julia is fun because of multiple dispatch. Maybe you want to have a look at Stefan’s talk at JuliaCon 2019.
1 Like