functional-programming - Julia 中有没有办法修改函数 f(x) 使其返回 f(x)*g(x)
问题描述
我在一些研究生研究中遇到了 Julia,并且已经用 C++ 完成了一些项目。我正在尝试将我的一些 C++ 工作“翻译”成 Julia,以比较性能等。
基本上我想做的是从 C++ 中实现类似函数库的东西,这样我就可以做类似的事情
g(x, b) = x*b # Modifier function
A = [1,2,...] # Some array of values
f(x) = 1 # Initialize the function
### This is the part that I am seeking
for i = 1:length(A)
f(x) = f(x)*g(x, A[i]) # This thing right here
end
###
然后能够调用f(x)
并获取g(x, _)
包含的所有术语的值(类似于bind
在 C++ 中使用)我不确定是否有本地语法来支持这一点,或者我是否需要研究一些符号表示的东西。任何帮助表示赞赏!
解决方案
您可能正在寻找这个:
julia> g(x, b) = x * b
g (generic function with 1 method)
julia> bind(g, b) = x -> g(x, b) # a general way to bind the second argument in a two argument function
bind (generic function with 1 method)
julia> A = [1, 2, 3]
3-element Vector{Int64}:
1
2
3
julia> const f = bind(g, 10) # bind a second argument of our specific function g to 10; I use use const for performance reasons only
#1 (generic function with 1 method)
julia> f.(A) # broadcasting f, as you want to apply it to a collection of arguments
3-element Vector{Int64}:
10
20
30
julia> f(A) # in this particular case this also works as A*10 is a valid operation, but in general broadcasting would be required
3-element Vector{Int64}:
10
20
30
特别是为了修复双参数函数的第一个和第二个参数,Julia Base 中的标准函数分别被调用Base.Fix1
和Base.Fix2
。
推荐阅读
- firebase - Firebase + Flutter:安装带有稍后可以与云同步的资产的应用程序
- python - 如何将唯一的班级成员添加到另一个班级
- php - $.getJSON 没有正确返回([object Object],未定义或什么都没有)
- java - 如何在 Spring Boot 中访问 kafka 流上下文之外的 GlobalKTable?
- python - pandas:具有条件公式和唯一值的 groupby
- android - 如何在 Jetpack Compose 中打开表情符号键盘?
- amazon-web-services - 为什么使用多容器端点而不是多模型端点?
- javascript - 未捕获的 DOMException:无法在“窗口”上执行“postMessage”:无法克隆 NodeList 对象
- python - Python循环在循环中保存两次到Excel电子表格选项卡
- c# - 使用 Mailgun 和 Httpclient 发送带有附件的电子邮件