勉強のためにListのAPIはなるべく使わない方向。
- // P20 (*) Remove the Kth element from a list.
- // 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[T](i: Int, xs: List[T]) =
- if(i < 0 || xs.size <= i) throw new NoSuchElementException
- else (xs.zipWithIndex.filter{_._2 != i}.map{_._1}, xs(i))
- def removeAtR[T](i: Int, xs: List[T]) = {
- def r(i: Int, xs: List[T], acc: List[T]): (List[T], T) = (i, xs) match {
- case (0, h :: t) => (acc.reverse ::: t, h)
- case (i, h :: t) => r(i - 1, t, h :: acc)
- }
- if(i < 0 || xs.size <= i) throw new NoSuchElementException else r(i, xs, Nil)
- }
No comments:
Post a Comment