勉強のためにListのAPIはなるべく使わない方向。
// P16 (**) Drop every Nth element from a list.
// Example:
// 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)
// not tail recursive version
def drop_nottail[T](n: Int, xs: List[T]): List[T] = xs match {
case h :: t if (n == 1) => drop_nottail(n - 1, t)
case h :: t => h :: drop_nottail(n - 1, t)
case Nil => xs
}
// tail recursive version
def drop_tail[T](nth: Int, xs: List[T]) = {
def recursive[T](n: Int, tail: List[T], acc: List[T]): List[T] = tail match {
case h :: t if (n == 1) => recursive(n - 1, t, acc)
case h :: t => recursive(n - 1, t, h :: acc)
case Nil => acc
}
recursive(nth, xs, Nil).reverse
}
// zipwithindex version
def drop_zipWithIndex[T](nth: Int, xs: List[T]) = {
xs.zipWithIndex.flatMap{
case (_, i) if (i + 1 == nth) => Nil // drop nth
case (e, _) => e :: Nil
}
}
val l: List[Int] = (1 to 100000).toList
//println(drop_nottail(3, l)) // StackOverflowError
//println(drop_tail(3, l))
println(drop_zipWithIndex(3, l))
解答例
そうまでして1行で書きたいってか!!
No comments:
Post a Comment