【问题标题】:How can I avoid StackOverflow Error on Julia?如何避免 Julia 上的 StackOverflow 错误?
【发布时间】:2019-02-06 00:55:47
【问题描述】:

这是一个小乘积函数,可以将常量列表、运算符列表和另一个常量列表转换为 Julia Expr。 该函数适用于较小的常量集,但是对于包含 100 个常量和 5 个运算符的列表,该函数会引发 StackOverflow。

function applyProduct(left, operators, right)
    prod = Iterators.product(left, operators, right)
    prod = Iterators.vcat(prod...)
    return Iterators.map(x -> Expr(:call, Symbol(x[2]), Symbol(x[1]), Symbol(x[3])), prod)
end

我的函数在 vcat 函数中爆炸:

ERROR: LoadError: StackOverflowError:
Stacktrace:
[1] promote_eltypeof(::Tuple{String,typeof(+),Expr}, ::Tuple{String,typeof(+),Expr}, ::Vararg{Any,N} where N) at .\abstractarray.jl:1211 (repeats 8406 times)
[2] _cat(::Val{1}, ::Tuple{String,typeof(*),Expr}, ::Vararg{Any,N} where N) at .\abstractarray.jl:1382
[3] #cat#104(::Val{1}, ::Function, ::Tuple{String,typeof(*),Expr}, ::Vararg{Any,N} where N) at .\abstractarray.jl:1511
[4] (::getfield(Base, Symbol("#kw##cat")))(::NamedTuple{(:dims,),Tuple{Val{1}}}, ::typeof(cat), ::Tuple{String,typeof(*),Expr}, ::Vararg{Any,N} where N) at .\none:0
[5] vcat(::Tuple{String,typeof(*),Expr}, ::Tuple{String,typeof(*),Expr}, ::Tuple{String,typeof(*),Expr}, ::Vararg{Any,N} where N) at .\abstractarray.jl:1449

这是一个堆栈溢出错误,因此数据以某种方式存储在堆栈中。我应该声明一些东西以将其保存在内存中吗?

我想将此操作应用于大量常量。也许我没有使用最有效的方法。

【问题讨论】:

    标签: out-of-memory julia stack-overflow


    【解决方案1】:

    您肯定想要预先分配。并避免显式枚举product 迭代器并使用映射

    function applyproduct(left, op, right)
        itr = Iterators.product(op, left, right)
        thestack = Vector{Expr}(undef, length(itr))
    
        for (i, t) in enumerate(itr)
            thestack[i] = Expr(:call, Symbol.(t)...)
        end
    
        return thestack
    end
    
    N = 500
    left = [String(rand('a':'z', rand(1:5))) for _ in 1:N]
    right = [String(rand('a':'z', rand(1:5))) for _ in 1:N]
    op = ["+", "-", "/", "^", "<", "≤"]
    
    applyproduct(left, op, right)
    # 1500000-element Array{Expr,1}:
    #  :(wtolz + kzyxh)
    #  :(wtolz - kzyxh)
    #  ⋮             
    

    此外,您可以通过以下方式避免 Expr 调用:

    :($(Symbol(t[1]))($(Symbol(t[2])), $(Symbol(t[3]))))  
    # :(adsf - sd)
    

    【讨论】:

      【解决方案2】:

      在需要它的元素之前不要具体化列表:

      using IterTools
      function applyProduct2(left, operators, right)
          prod = Iterators.product(left, operators, right)
          return IterTools.imap(x -> Expr(:call, Symbol(x[2]), Symbol(x[1]), Symbol(x[3])), prod)
      end
      

      请注意,您可能需要安装 IterTools.jl 库。

      话虽如此,您的代码在 vcat 上崩溃,您尝试使用大量参数调用它。如果您必须实现,请改用vec(collect(prod))。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-20
        • 1970-01-01
        • 2014-09-05
        • 2012-07-06
        • 2021-09-13
        • 1970-01-01
        相关资源
        最近更新 更多