Phuoc
Phuoc

Reputation: 1103

Access function defined in another function

Is it possible to access 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

Upvotes: 3

Views: 150

Answers (2)

Michael K. Borregaard
Michael K. Borregaard

Reputation: 8044

No. In julia, it is often more ideomatic 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 use case? You can define a custom type, give it a function field, and then make the type callable (a closure) to achieve the behaviour you want. But whether that is the best way of solving your issue in julia is a different question.

Upvotes: 5

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22255

You can do this if your function f is an instance of a callable type, containing a 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 is always a fixed function, then you can introduce it via an internal constructor.

But to echo Lyndon's comments above, a better question is, why would you do this instead of something relying more on julia's dynamic dispatch features?

Upvotes: 1

Related Questions