hja*_*jab 3 first-class-functions julia
Julia文档声明函数是第一类对象.我理解这意味着我应该能够像使用旧数据类型一样使用和定义它们.
因此,我很惊讶
function a(b::Int64)
if b > 0
c = 1
else
c = -1
end
end
a(2)
Run Code Online (Sandbox Code Playgroud)
同时工作得很漂亮
function d(e::Int64)
if e > 0
println("Positive argument")
function f()
println("Return positive")
return e
end
else
println("Negative argument")
function f()
println("Return negative")
return e
end
end
return f
end
Run Code Online (Sandbox Code Playgroud)
在使用时有效,但做了非常直观的事情:
>>> g = d(2)
Positive argument
(::f) (generic function with 1 method)
>>> g()
Return negative
2
Run Code Online (Sandbox Code Playgroud)
或者:
>>> g = d(-2)
Negative argument
ERROR: UnderVarError: f not defined
Run Code Online (Sandbox Code Playgroud)
这可能比返回意想不到的东西更有用,但更令人困惑的是.
我希望f将返回相应分支的版本.我对朱莉娅中的函数定义如何出错的理解在哪里?
我可以向您展示如何解决问题,但您描述的实际行为是一个已知问题https://github.com/JuliaLang/julia/issues/15602.
一般来说,如果你这样做:
function d(e::Int64)
if e > 0
println("Positive argument")
f = function()
println("Return positive")
return e
end
else
println("Negative argument")
f = function()
println("Return negative")
return e
end
end
return f
end
Run Code Online (Sandbox Code Playgroud)
一切正常.不同之处在于您创建了一个匿名函数并将其分配给变量.