Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access function defined in another function

Tags:

julia

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
like image 693
Phuoc Avatar asked Jul 29 '26 02:07

Phuoc


1 Answers

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.

like image 117
Michael K. Borregaard Avatar answered Aug 02 '26 18:08

Michael K. Borregaard