P18 (**) Extract a slice from a list

来源:互联网 发布:乎肉的做法大全 编辑:程序博客网 时间:2024/04/29 17:55

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)

//18def 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)}

参考答案



0 0
原创粉丝点击