gpt4 book ai didi

scala - 为什么如果 V < : Seq[Int] when V is a Seq descendant map and zip operations return a Seq[Int]

转载 作者:行者123 更新时间:2023-12-01 13:18:44 30 4
gpt4 key购买 nike

如标题中所述,我不明白为什么这些函数无法编译并要求 Seq。

def f1[V <: Seq[Int]](v: V): V = v.map(_ + 1)
def f2[V <: Seq[Int]](v: V): V = v.zip(v).map{ case (a, b) => a + b }

error: type mismatch;
found : Seq[Int]
required: V

我有以下解决方法:

def f1[V <: Seq[Int]](v: V): V = v.map(_ + 1).asInstanceOf[V]
def f2[V <: Seq[Int]](v: V): V = v.zip(v).map{ case (a, b) => a + b }.asInstanceOf[V]

但我想知道是否存在其他解决方案。如果不是这样的话,类型转换这样的东西的成本是多少,它是 O(1) 还是 O(n) 与 n 的 Seq 大小。

最佳答案

因为

v.map(_ + 1).asInstanceOf[V]

很容易失败:map只保证返回 Seq[Int] ,它可能恰好是 V 的一个实例,也可能不是当您运行代码时。

一个例子是 V = SeqView.Filtered , 其中map返回 SeqView.Mapped .

If not what is the cost of casting something like that, is it O(1) or O(n) with n the Seq size.

类型转换成本asInstanceOf总是 O(1)。在某些情况下,它实际上是空操作,成本为 0。

关于scala - 为什么如果 V < : Seq[Int] when V is a Seq descendant map and zip operations return a Seq[Int],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029863/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com