更新序列中的多个值 [英] Update multiple values in a sequence
问题描述
要获得一个更新了一个值的序列,可以使用
To get a sequence with one value updated, one can use
seq.updated(index, value)
我想为一系列元素设置一个新值.有图书馆功能吗?我目前使用以下功能:
I want to set a new value for a range of elements. Is there a library function for that? I currently use the following function:
def updatedSlice[A](seq: List[A], ind: Iterable[Int], value: A): List[A] =
if (ind.isEmpty) seq
else updatedSlice(seq.updated(ind.head, value), ind.tail, value)
除了需要编写函数外,这似乎效率低下,并且仅适用于列表,而不适用于 Seq
和 String
的任意子类.所以,
Besides the need of writing function, this seems to be inefficient, and also works only for lists, rather than arbitrary subclasses of Seq
and String
s. So,
- 有执行它的方法吗?
- 如何对函数进行参数化以获取(并返回)
Seq [A]
的某些子类?
- is there a method that performs it?
- how can I parametrize the function to take (and return) some subclass of
Seq[A]
?
推荐答案
在计算机上没有人说过:
No one at a computer has said:
scala> (1 to 10).toSeq patch (3, (1 to 5), 3)
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 1, 2, 3, 4, 5, 7, 8, 9, 10)
保存@Marth的绿色支票.
Save your green checks for @Marth.
请注意,他们仍在努力.
Note they're still working on it.
https://issues.scala-lang.org/browse/SI-8474
关于不经常使用的API的一些看法.
Which says something about less-frequently-used API.
更新:我第二次看了这个问题,发现我读错了,哦:
Update: I glanced at the question a second time and saw that I misread it, oh well:
scala> implicit class x[A](as: Seq[A]) {
| def updatedAt(is: collection.Traversable[Int], a: A) = {
| (as /: is) { case (xx, i) => xx updated (i, a) } } }
defined class x
scala> (1 to 10) updatedAt (Seq(3,6,9), 0)
res9: Seq[Int] = Vector(1, 2, 3, 0, 5, 6, 0, 8, 9, 0)
打一场轻松的高尔夫球.
Just a relaxing round of golf.
更新:s/放松/烦人
看起来它需要更多类型参数,但是我没有时间限制.
Looks like it needs more type params, but I don't have a time slice for it.
scala> implicit class slicer[A, B[_] <: Seq[_]](as: B[A]) {
| def updatedAt[That<:B[_]](is: Traversable[Int], a: A)(implicit cbf: CanBuildFrom[B[A], A, That]) =
| (as /: is) { case (x,i) => x updated[A,That] (i,a) }}
<console>:15: error: type arguments [A,That] conform to the bounds of none of the overloaded alternatives of
value updated: [B >: _$1, That](index: Int, elem: B)(implicit bf: scala.collection.generic.CanBuildFrom[Seq[_$1],B,That])That <and> [B >: A, That](index: Int, elem: B)(implicit bf: scala.collection.generic.CanBuildFrom[Repr,B,That])That
(as /: is) { case (x,i) => x updated[A,That] (i,a) }}
^
谁甚至知道更新已超载?
Who even knew updated was overloaded?
我最喜欢的奥德斯基语录:
My new favorite Odersky quote:
我一直玩到它变得太乏味为止.
I played with it until it got too tedious.
这篇关于更新序列中的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!