在列表的指定位置插入新元素 [英] Insert a new element in a specified position of a list
问题描述
List 没有内置函数或方法可以允许用户在 List 的某个位置添加新元素.我已经编写了一个执行此操作的函数,但我不确定以这种方式执行此操作是否是一个好主意,即使它运行得非常好:
There is no built-in function or a method of a List that would allow user to add a new element in a certain position of a List. I've wrote a function that does this but I'm not sure that its a good idea to do it this way, even though it works perfectly well:
def insert(list: List[Any], i: Int, value: Any) = {
list.take(i) ++ List(value) ++ list.drop(i)
}
用法:
scala> insert(List(1,2,3,5), 3, 4)
res62: List[Any] = List(1, 2, 3, 4, 5)
推荐答案
类型安全
我看到的最明显的事情是缺乏类型安全/丢失类型信息.我将使该方法在列表的元素类型中通用:
Type Safety
The most glaring thing I see is the lack of type safety / loss of type information. I would make the method generic in the list's element type:
def insert[T](list: List[T], i: Int, value: T) = {
list.take(i) ++ List(value) ++ list.drop(i)
}
风格
如果正文只包含一个表达式,则不需要花括号:
Style
If the body only consists of a single expression, there is no need for curly braces:
def insert[T](list: List[T], i: Int, value: T) =
list.take(i) ++ List(value) ++ list.drop(i)
效率
@Marth 关于使用 List.splitAt
避免两次遍历列表也是一个好方法:
Efficiency
@Marth's comment about using List.splitAt
to avoid traversing the list twice is also a good one:
def insert[T](list: List[T], i: Int, value: T) = {
val (front, back) = list.splitAt(i)
front ++ List(value) ++ back
}
界面
一次插入多个值可能会很方便:
Interface
It would probably be convenient to be able to insert more than one value at a time:
def insert[T](list: List[T], i: Int, values: T*) = {
val (front, back) = list.splitAt(i)
front ++ values ++ back
}
接口,取2
你可以把它作为List
的扩展方法:
implicit class ListWithInsert[T](val list: List[T]) extends AnyVal {
def insert(i: Int, values: T*) = {
val (front, back) = list.splitAt(i)
front ++ values ++ back
}
}
List(1, 2, 3, 6).insert(3, 4, 5)
// => List(1, 2, 3, 4, 5, 6)
结束语
但是请注意,插入列表中间并不适合 cons 列表.使用(可变)链表或动态数组会更好.
Closing remarks
Note, however, that inserting into the middle of the list is just not a good fit for a cons list. You'd be much better off with a (mutable) linked list or a dynamic array instead.
这篇关于在列表的指定位置插入新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!