访问函数在另一个函数中定义

Phu*_*uoc 3 julia

是否可以访问julia中另一个函数中定义的函数?例如:

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
Run Code Online (Sandbox Code Playgroud)

Mic*_*ard 5

在朱利亚,将模块用于本地功能通常更具思想性

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)
Run Code Online (Sandbox Code Playgroud)

用例是什么?您可以定义自定义类型,为其指定一个函数字段,然后使类型可调用(闭包)以实现您想要的行为.但是,这是否是解决你在朱莉娅问题的最佳方式是一个不同的问题.

  • @LyndonWhite,只是为了笑,但请查看这篇文章和Jeff B的回复:http://stackoverflow.com/questions/39133424/how-to-create-a-single-dispatch-object-oriented-class -in-朱莉娅 - 即-行为-1 (2认同)