由 Julia `map` 调用的函数的不可迭代参数?

问题描述 投票:0回答:1

我有一个

for
循环,必须调用
map
函数,其函数
f
使用向量和标量的元素来执行简单的乘法。我希望标量是每次迭代时循环变量的值。如何在 Julia 中执行此操作,而无需在循环的每次迭代中重新声明函数?例如,

some_vector = [1, 2, 3, 4]
n_indices = 5
for i in 1:n_indices
  function foo(ele)
    ele*i 
  end
  result = map(foo, some_vector)
  # other complicated logic ...
end

所以我希望

foo
类似于
foo(ele, i)
,其中
ele
是可迭代的元素,而
i
只是一个标量。我知道在这种情况下我可以只使用匿名函数,因为这里的逻辑非常简单,但是
foo
实际上很长,给它一个名称更具表现力,所以将
foo
从循环中拉出来会更容易如果可能的话,这是理想的选择。

julia
1个回答
0
投票

由于您正在使用矢量,惯用的方法是使用广播

some_vector = [1, 2, 3, 4]
n_indices = 5

function foo(ele, i)
  ele*i 
end

for i in 1:n_indices
  result = foo.(some_vector, i)
  # other complicated logic ...
end
© www.soinside.com 2019 - 2024. All rights reserved.