16
scala> drop(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
res0: List[Symbol] = List('a, 'b, 'd, 'e, 'g, 'h, 'j, 'k)
参考答案:
其中关于zip 和filter的用法见http://blog.youkuaiyun.com/springlustre/article/details/48804911
object P16 {
// Simple recursion.
def dropRecursive[A](n: Int, ls: List[A]): List[A] = {
def dropR(c: Int, curList: List[A]): List[A] = (c, curList) match {
case (_, Nil) => Nil
case (1, _ :: tail) => dropR(n, tail)
case (_, h :: tail) => h :: dropR(c - 1, tail)
}
dropR(n, ls)
}
// Tail recursive.
def dropTailRecursive[A](n: Int, ls: List[A]): List[A] = {
def dropR(c: Int, curList: List[A], result: List[A]): List[A] = (c, curList) match {
case (_, Nil) => result.reverse
case (1, _ :: tail) => dropR(n, tail, result)
case (_, h :: tail) => dropR(c - 1, tail, h :: result)
}
dropR(n, ls, Nil)
}
// Functional.
def dropFunctional[A](n: Int, ls: List[A]): List[A] =
ls.zipWithIndex filter { v => (v._2 + 1) % n != 0 } map { _._1 }
} 17.
scala> split(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
res0: (List[Symbol], List[Symbol]) = (List('a, 'b, 'c),List('d, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
//17 def split[A](N:Int,ls:List[A])={ val(a,b)=ls.zipWithIndex span(_._2<N) (a.map(_._1),b.map(_._1)) }除此之外,也可以用take和drop更加方便,还可以直接用splitAt函数
646

被折叠的 条评论
为什么被折叠?



