我正在尝试构建一个接受2个输入limits
和Function
的函数,所以我写了以下内容:
function Σ(limits, f::Function)
@show limits
@show f
end
Σ((i=1:3), :(x->x^2))
但是它无法运行,出现以下错误:
错误:LoadError:函数Σ不接受关键字参数
我不明白我是否应该在函数声明或函数执行中更改某些内容?
答案 0 :(得分:0)
看起来错误在于传递Function
时,在解决此问题的正确代码下面:
function Σ(limits, f::Function)
prefix, start, stop = limits.args[2].args
out = 0.0
for i=start:stop
out += f(i)
end
out
end
result = Σ(:(i=1:6), n->(6n + 2))
@show result
其他4种解决方法是:
# Using Pair
julia> function Σ(limits, f::Function)
out = 0.0
start = limits.first
stop = limits.second
for i = start:stop
out += f(i)
end
out
end
Σ (generic function with 1 method)
julia> Σ(1=>6, n->(6n + 2))
138.0
然后
# Using range
julia> function Σ(range, f::Function)
out = 0.0
for i = range
out += f(i)
end
out
end
Σ (generic function with 1 method)
julia> Σ(1:6, n->(6n + 2))
138.0
最后一个选项,可以重写为:
function Σ(range, f::Function)
out = 0.0
(for i = range; out += f(i) ; end)
out
end
result = Σ(1:6, n->(6n + 2))
@show result
通过使用现有的sum
函数,下面是单行输出:
Σ(range, f::Function) = sum(f(i) for i in range)
result = Σ(1:6, n->(6n + 2))
@show result
或者,简单地作为:
f(n) = 6n + 2
result = sum(f(n) for n=1:6)
@show result
其中也可以简化为:
f(n) = 6n + 2
result = sum(f, 1:6)
@show result