相关疑难解决方法(0)

我可以将类型信息添加到Julia中的函数参数吗?

我可以将类型信息添加到函数的参数中吗?

请考虑以下示例:

function f{T} (func, x::Int)
    output = Dict{Int, Any}()
    output[x] = func(x)
    return output
end 
Run Code Online (Sandbox Code Playgroud)

我不喜欢我必须说Any的字典的值类型.我宁愿做以下事情:

function f{T} (func::Function{Int->T}, x::Int)
    output = Dict{Int, T}()
    output[x] = func(x)
    return output
end 
Run Code Online (Sandbox Code Playgroud)

我可以提供类似这样的函数的类型提示吗?我有点想说以下

f :: (Int -> T), Int -> Dict{Int, T}
Run Code Online (Sandbox Code Playgroud)

julia

20
推荐指数
1
解决办法
2650
查看次数

当函数传递函数时,Julia编译器似乎不会优化

第二次编辑: github上的这个拉取请求将解决问题.只要有人运行Julia v0.5 +,匿名函数就会像常规函数一样快.案件已经结案.

编辑:我已经将问题和函数定义更新为更一般的情况.

举一个简单的例子,当函数传递函数或在函数中定义函数时,Julia编译器似乎不会优化.这让我感到惊讶,因为这在优化包中非常普遍.我是正确还是我做了一些愚蠢的事情?一个简单的例子如下:

f(a::Int, b::Int) = a - b    #A simple function

function g1(N::Int, fIn::Function)   #Case 1: Passing in a function
    z = 0
    for n = 1:N
        z += fIn(n, n)
    end
end

function g2(N::Int)   #Case 2: Function defined within a function
    fAnon = f
    z = 0
    for n = 1:N
        z += fAnon(n, n)
    end
    return(z)
end

function g3(N::Int)   #Case 3: Function not defined within function
    z = 0
    for n …
Run Code Online (Sandbox Code Playgroud)

julia

15
推荐指数
1
解决办法
541
查看次数

在Julia中使用匿名函数的性能损失

我注意到在Julia中使用匿名函数会导致性能下降.为了说明我有两个quicksort实现(取自Julia发行版中的微观性能基准).第一种按升序排序

function qsort!(a,lo,hi)
    i, j = lo, hi
    while i < hi
        pivot = a[(lo+hi)>>>1]
        while i <= j
            while a[i] < pivot; i += 1; end
            while pivot < a[j]; j -= 1; end
            if i <= j
                a[i], a[j] = a[j], a[i]
                i, j = i+1, j-1
            end
        end
        if lo < j; qsort!(a,lo,j); end
        lo, j = i, hi
    end
    return a
end
Run Code Online (Sandbox Code Playgroud)

第二个需要一个额外的参数:一个匿名函数,可用于指定升序或降序排序,或比较更奇特的类型

function qsort_generic!(a,lo,hi,op=(x,y)->x<y)
    i, j = lo, hi
    while i < hi
        pivot = …
Run Code Online (Sandbox Code Playgroud)

performance anonymous-function julia

5
推荐指数
3
解决办法
892
查看次数

标签 统计

julia ×3

anonymous-function ×1

performance ×1