带有向量输入的内部构造函数中的方法错误

问题描述 投票:0回答:1

我正在尝试实现一个 SparsePolynomial 类型,它将术语存储为链接列表中的项目(来自 DataStructures.jl),并使用指向链接列表中的项目的字典。该结构将输入作为

Term
的向量,这是我创建的另一个结构。当我放入非零
Term
向量时,这将起作用。当我尝试使用内部构造函数使用
SparsePolynomial()
创建零多项式时,如下所示,它返回错误:
MethodError: Cannot convert an object of type Vector{Term} to an object of type MutableLinkedList{Term}
。我已经为
zero(Term)
定义了一个方法,否则它可以工作。

struct PolynomialSparse

  terms:: MutableLinkedList{Term} 
  dict:: Dict{Int, DataStructures.ListNode{Term}} 

  #Inner constructor of the 0 polynomial
  PolynomialSparse() = new([zero(Term)])
  
  #Inner constructor of polynomial based on arbitrary list of terms
  function PolynomialSparse(terms::Vector{Term})
      #Filter the vector so that there is not more than a single zero term
      terms = sort(filter((t)->!iszero(t), terms))
      if isempty(terms)
          terms = [zero(Term)]
      end
      # initialise empty linked list and dictionary
      lst = MutableLinkedList{Term}()
      dict = Dict{Int, DataStructures.ListNode{Term}}()
      # create list and dictionary out of the vector of terms
      for t in terms
          insert_sorted!(lst, dict, t.degree, t)
      end

      return new(lst, dict)
  end
end
vector struct constructor linked-list julia
1个回答
0
投票

我相信我的问题是我试图用零项向量的字段创建一个

PolynomialSparse
- 我困惑的根源在于多项式的内部构造函数是一个函数,它将项向量作为一个输入,但结构本身具有 1. 可变链表和 2. 字典的字段,因此它不起作用。我发现到目前为止有效的解决方案是将零多项式的内部构造函数替换为:

PolynomialSparse() = new(MutableLinkedList{Term}(zero(Term)), Dict{Int, DataStructures.ListNode{Term}}(0=>DataStructures.ListNode{Term}(zero(Term))))
© www.soinside.com 2019 - 2024. All rights reserved.