P18 (**) Extract a slice from a list

本文介绍了Scala中实现列表切片的几种方法,包括使用drop和take组合、直接使用drop和dropRight以及递归方法。通过具体示例展示了如何从列表中获取指定范围内的元素。

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

Given two indices, I and K, the slice is the list containing the elements from and including the Ith element up to but not including the Kth element of the original list. Start counting the elements with 0.

Example:

scala> slice(3, 7, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))

res0: List[Symbol] = List('d, 'e, 'f, 'g)

//18
def slice[A](n1:Int,n2:Int,ls:List[A])={
  val len=ls.length
  ls.drop(n1).dropRight(len-n2)
}

也可以用drop和take结合的方法,

ls drop s take (e - (s max 0))
也可以用递归的方法
def slice2[A](n1:Int,n2:Int,ls:List[A]):List[A]=(n1,n2,ls) match{
  case(_,_,Nil) =>Nil
  case(_,n2,_) if(n2<=0) =>Nil
  case(n1,n2,h::tail) if(n1<=0)=>h::slice2(0,n2-1,tail)
  case(n1,n2,h::tail) =>slice(n1-1,n2-1,tail)
}

参考答案



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值