首页 > 解决方案 > 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)

I'm a novice and new to Julia. Is there a way to accomplish this similar to my 2nd attempt above? Thanks

标签: functiondictionaryjuliaanonymous-function

解决方案


您可以像这样使用匿名函数语法:

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()

推荐阅读