将`limits'作为函数参数传递

时间:2018-08-20 17:30:46

标签: julia

我正在尝试构建一个接受2个输入limitsFunction的函数,所以我写了以下内容:

function Σ(limits, f::Function)
    @show limits
    @show f
end

Σ((i=1:3), :(x->x^2))

但是它无法运行,出现以下错误:

  

错误:LoadError:函数Σ不接受关键字参数

我不明白我是否应该在函数声明或函数执行中更改某些内容?

1 个答案:

答案 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

enter image description here

其他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