创建函数字典的更好方法
Better way to create dictionary of functions
#attempt 1: works
f(x::Int64) = x +1
my_functions = Dict("f" => f)
#attempt 2: does not work, something is wrong
new_functions = Dict("g" => g(x::Int64) = x + 5)
我是 Julia 的新手。有没有办法像我上面的第二次尝试那样完成这个?谢谢
您可以像这样使用匿名函数语法:
new_functions = Dict("g" => x::Int64 -> x + 5)
您可以在 Julia 手册中阅读有关如何使用它们的详细信息:https://docs.julialang.org/en/latest/manual/functions/#man-anonymous-functions-1。
编辑:请注意,如果您最初只向字典添加一个函数,则其类型将过于受限,例如:Dict{String,getfield(Main, Symbol("##3#4"))}
,例如:
julia> new_functions = Dict("g" => x::Int64 -> x + 5)
Dict{String,getfield(Main, Symbol("##15#16"))} with 1 entry:
"g" => ##15#16()
所以你可能应该像这样明确指定类型:
julia> new_functions = Dict{String, Function}("g" => x::Int64 -> x + 5)
Dict{String,Function} with 1 entry:
"g" => ##23#24()
或者在最初的字典中至少添加两个条目:
julia> new_functions = Dict("g" => x::Int64 -> x + 5, "h" => x -> x+1)
Dict{String,Function} with 2 entries:
"g" => ##11#13()
"h" => ##12#14()
为了完整起见:也可以使用普通的多行函数语法作为表达式,这将创建一个带有名称的函数对象(如 JavaScript 中的 "named function expression";这如果你需要递归就很方便):
julia> Dict("g" => function g(x::Int); x + 5; end)
Dict{String,typeof(g)} with 1 entry:
"g" => g
行中的第一个 ;
在这里是必需的。如您所见,@Bogumił 关于输入 Dict
的注意事项也适用。
也可以使用短格式语法,但必须将表达式放在括号中:
Dict("g" => (g(x::Int) = x + 5))
#attempt 1: works
f(x::Int64) = x +1
my_functions = Dict("f" => f)
#attempt 2: does not work, something is wrong
new_functions = Dict("g" => g(x::Int64) = x + 5)
我是 Julia 的新手。有没有办法像我上面的第二次尝试那样完成这个?谢谢
您可以像这样使用匿名函数语法:
new_functions = Dict("g" => x::Int64 -> x + 5)
您可以在 Julia 手册中阅读有关如何使用它们的详细信息:https://docs.julialang.org/en/latest/manual/functions/#man-anonymous-functions-1。
编辑:请注意,如果您最初只向字典添加一个函数,则其类型将过于受限,例如:Dict{String,getfield(Main, Symbol("##3#4"))}
,例如:
julia> new_functions = Dict("g" => x::Int64 -> x + 5)
Dict{String,getfield(Main, Symbol("##15#16"))} with 1 entry:
"g" => ##15#16()
所以你可能应该像这样明确指定类型:
julia> new_functions = Dict{String, Function}("g" => x::Int64 -> x + 5)
Dict{String,Function} with 1 entry:
"g" => ##23#24()
或者在最初的字典中至少添加两个条目:
julia> new_functions = Dict("g" => x::Int64 -> x + 5, "h" => x -> x+1)
Dict{String,Function} with 2 entries:
"g" => ##11#13()
"h" => ##12#14()
为了完整起见:也可以使用普通的多行函数语法作为表达式,这将创建一个带有名称的函数对象(如 JavaScript 中的 "named function expression";这如果你需要递归就很方便):
julia> Dict("g" => function g(x::Int); x + 5; end)
Dict{String,typeof(g)} with 1 entry:
"g" => g
行中的第一个 ;
在这里是必需的。如您所见,@Bogumił 关于输入 Dict
的注意事项也适用。
也可以使用短格式语法,但必须将表达式放在括号中:
Dict("g" => (g(x::Int) = x + 5))