【问题标题】:Julia - implementing to_index(::Symbol)Julia - 实现 to_index(::Symbol)
【发布时间】:2019-08-01 07:00:44
【问题描述】:

以下加载失败。它说问题出在 to_index 方法上,但仅在使用冒号运算符时才会发生。

S = InputOhlcSeries{Int}(5)
push!(S, 0,0,0,1)
push!(S, 0,0,0,2)
push!(S, 0,0,0,3)
push!(S, 0,0,0,4)
push!(S, 0,0,0,5)
push!(S, 0,0,0,6)
@assert S[end, :close] == 6 # Works fine
@assert S[:, 4] == [2,3,4,5,6] # Works fine
@assert S[:, :close] == [2,3,4,5,6] # Will fail here

ERROR: LoadError: LoadError: ArgumentError: invalid index: close of type Symbol
Stacktrace:
 [1] to_index(::Symbol) at ./indices.jl:270
 [2] to_index(::InputOhlcSeries{Int64}, ::Symbol) at ./indices.jl:247
 [3] to_indices at ./indices.jl:298 [inlined]
 [4] to_indices at ./indices.jl:294 [inlined]
 [5] getindex(::InputOhlcSeries{Int64}, ::Function, ::Symbol) at ./abstractarray.jl:927
 [6] top-level scope at none:0
 [7] include at ./boot.jl:326 [inlined]


using Match

mutable struct InputOhlcSeries{T} <: AbstractArray{T,2}
    data::CircularBuffer{Vector{T}}
    function InputOhlcSeries{T}(length::Int) where T
        data = CircularBuffer{Vector{T}}(length)
        fill!(data, [0,0,0,0])
        new{T}(data)
    end
end

@inline Base.getindex(S::InputOhlcSeries, i::Int, j::Int) = S.data[i][j]
@inline Base.setindex!(S::InputOhlcSeries, value, i::Int, j::Int) = S.data[i][j] = value
Base.size(S::InputOhlcSeries) = (length(S.data), 4)
Base.eltype(::Type{InputOhlcSeries{T}}) where {T} = T

@inline Base.push!(S::InputOhlcSeries, open, high, low, close) = push!(S.data, [open, high, low, close])

@inline function Base.getindex(S::InputOhlcSeries, r::Int, c::Symbol)
    S[r, to_index(c)]
end

@inline function Base.setindex!(S::InputOhlcSeries, value, r::Int, c::Symbol)
    S[r, to_index(c)] = value
end

@inline function to_index(r::Symbol)::Int
  @match r begin
    :open => 1
    :high => 2
    :low  => 3
    :close  => 4
    _      => throw(ArgumentError("Expected one of :open, :high, :low, :close"))
  end
end

【问题讨论】:

  • 应该是什么?
  • @OscarSmith 不确定您的意思。看最后一个方法 to_index()。
  • 你完成import Base.to_index了吗?您需要这样做来扩展to_index,或者编写您的函数定义,如function Base.to_index(r::Symbol)
  • @CameronBieganek 出于某种原因导致 ERROR: LoadError: UndefVarError: to_index not defined

标签: julia


【解决方案1】:

制作了以下模组:

import Base: to_index

@inline Base.getindex(S::InputOhlcSeries, r::Int, c::Symbol) = S[r, to_index(S, c)]

@inline function Base.setindex!(S::InputOhlcSeries, value, r::Int, c::Symbol)
    S[r, to_index(S, c)] = value
end

@inline Base.push!(S::InputOhlcSeries, open, high, low, close) = push!(S.data, [open, high, low, close])

function to_index(S::InputOhlcSeries, s::Symbol)
  @match s begin
    :open  => 1
    :high  => 2
    :low   => 3
    :close => 4
    _      => throw(ArgumentError("Expected one of :open, :high, :low, :close"))
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多