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) }
参考答案