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, 'ddef 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 }