Access function defined in another function
Is it possible to access a function defined in another function in julia? For example:
julia> function f(x)
function g(x)
x^2
end
x * g(x)
end
f (generic function with 1 method)
julia> f(2)
8
julia> f.g(2)
ERROR: type #f has no field g
in eval_user_input(::Any, ::Base.REPL.REPLBackend) at ./REPL.jl:64
in macro expansion at ./REPL.jl:95 [inlined]
in (::Base.REPL.##3#4{Base.REPL.REPLBackend})() at ./event.jl:68
source to share
Not. In julia it is often more idealistic to use a module for local functions
module F
function g(x)
x^2
end
function f(x)
x * g(x)
end
export f
end
using F
f(2)
F.g(2)
What's the precedent? You can define a custom type, give it a function field, and then make the type callable (closure) to achieve the behavior you want. But whether this is the best way to solve your problem in julia is another question.
source to share
You can do this if your function f
is an instance of a callable type containing the function g
as an accessible field:
julia> type F g::Function end julia> function(p::F)(x) # make type F a callable type x * p.g(x) end julia> f = F(function (x) return x.^2 end) # initialise with a function F(#1) julia> f(2) 8 julia> f.g (::#1) (generic function with 1 method)
If g
it is always a fixed function, you can inject it through the internal constructor.
But to echo Lyndon's comments above, the better question is, why would you need to do this instead of relying more on julia's dynamic dispatching features?
source to share