如何将元素排入可迭代队列,例如队列[列表[节点]]?
How can I enqueue an element to a queue of iterables, e.g. Queue[List[Node]]?
scala.collection.immutable.Queue
的 enqueue
函数被重载。
def enqueue[B >: A](elem: B]): Queue[B]
def enqueue[B >: A](iter: Iterable[B]): Queue[B]
第一个签名允许您将单个项目添加到队列中,而后者允许您添加多个项目。
我正在研究一种图形搜索算法,并使用队列来跟踪我到目前为止所遍历的路径 (List[Node]
)。但是当我尝试对路径进行排队时,编译器假定我想使用具有可迭代签名的函数并抛出错误。
val path = List(Node(0), Node(1), Node(4))
val q: Queue[List[Node]] = Queue[List[Node]]().enqueue(path)
// Expression of type Queue[Product with Serializable] does not conform to expected type Queue[List[Node]]
我可以通过将路径包装在另一个列表中来解决这个问题,但这是强制的并且不太清楚。
val q: Queue[List[Node]] = Queue[List[Node]]().enqueue(List(path))
// compiles
有更好的方法吗?
编辑
我还注意到 :+
运算符仅用于对单个元素进行排队,我更喜欢它。
val q: Queue[List[Node]] = Queue[List[Node]]() :+ path
你可以把enqueue
的类型参数更明确一点:
q.enqueue[List[Node]](path)
应该适合你。
问题不在于 enqueue
方法。您正在使用运算符 ++
, which accepts a list of B
(GenTraversableOnce[B]
, to be more precisely). You may want to use :+
运算符。
scala.collection.immutable.Queue
的 enqueue
函数被重载。
def enqueue[B >: A](elem: B]): Queue[B]
def enqueue[B >: A](iter: Iterable[B]): Queue[B]
第一个签名允许您将单个项目添加到队列中,而后者允许您添加多个项目。
我正在研究一种图形搜索算法,并使用队列来跟踪我到目前为止所遍历的路径 (List[Node]
)。但是当我尝试对路径进行排队时,编译器假定我想使用具有可迭代签名的函数并抛出错误。
val path = List(Node(0), Node(1), Node(4))
val q: Queue[List[Node]] = Queue[List[Node]]().enqueue(path)
// Expression of type Queue[Product with Serializable] does not conform to expected type Queue[List[Node]]
我可以通过将路径包装在另一个列表中来解决这个问题,但这是强制的并且不太清楚。
val q: Queue[List[Node]] = Queue[List[Node]]().enqueue(List(path))
// compiles
有更好的方法吗?
编辑
我还注意到 :+
运算符仅用于对单个元素进行排队,我更喜欢它。
val q: Queue[List[Node]] = Queue[List[Node]]() :+ path
你可以把enqueue
的类型参数更明确一点:
q.enqueue[List[Node]](path)
应该适合你。
问题不在于 enqueue
方法。您正在使用运算符 ++
, which accepts a list of B
(GenTraversableOnce[B]
, to be more precisely). You may want to use :+
运算符。