gpt4 book ai didi

functional-programming - Julia 中有没有一种方法可以修改函数 f(x) 使其返回 f(x)*g(x)

转载 作者:行者123 更新时间:2023-12-04 14:05:55 26 4
gpt4 key购买 nike

我在一些研究生研究中遇到了 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.Fix1Base.Fix2 .

关于functional-programming - Julia 中有没有一种方法可以修改函数 f(x) 使其返回 f(x)*g(x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68536525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com