P20 (*) P21 (*)Remove the Kth element from a list;Insert an element at a given position into a list.

本文介绍Scala中如何通过removeAt和insertAt函数实现列表元素的移除与插入操作,并提供了具体的函数定义与使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Return the list and the removed element in a Tuple. Elements are numbered from 0.

Example:

scala> removeAt(1, List('a, 'b, 'c, 'd))
res0: (List[Symbol], Symbol) = (List('a, 'c, 'd),'b)
def removeAt[A](n:Int,ls:List[A]):(List[A],A)=(n,ls) match{
  case (n,ls) if(n<0) => throw new NoSuchElementException
  case (_,Nil) => throw new NoSuchElementException
  case (_,_)   =>(ls.take(n):::ls.drop(n+1),ls.drop(n).head)
}

也可以用splitAt函数
参考答案
 
 
 
Example:
scala> insertAt('new, 1, List('a, 'b, 'c, 'd))
res0: List[Symbol] = List('a, 'new, 'b, 'c, 'd
def insertAt[A](e:A,n:Int,ls:List[A]):List[A]={
  ls.take(n):::List(e):::ls.drop(n)
}

参考答案
def insertAt[A](e: A, n: Int, ls: List[A]): List[A] = ls.splitAt(n) match {
    case (pre, post) => pre ::: e :: post
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值