function - 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
解决方案
您可以像这样使用匿名函数语法:
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()
推荐阅读
- reactjs - npm 错误!ERESOLVE 无法解析 React Native 中的依赖树
- kotlin - 编写此代码的最佳方法,希望减少 if else 的数量
- python - 具有 gpu_shared4 扩展的 GL 版本 2.1 在 Ubuntu 18.04.5 LTS 上不支持作为来宾 VM
- r - 在 rowSums 中使用点 (.)
- flutter - 如何从右到左滚动 singlechildscrollview 水平轴
- vue.js - 在 vue.js 中验证当前日期时间之后的日期
- url - TYPO3 中带有 config.yaml 的多语言环境中的路由
- reactjs - 覆盖新路线时,React Native先前的路线会改变位置
- javascript - 如何在svelte中将参数传递给模态
- node.js - Node.JS Puppeteer:MaxListenersExceededWarning:检测到可能的 EventEmitter 内存泄漏。(Heroku 部署)