Wednesday, November 10, 2010

S21

S-99: Ninety-Nine Scala Problemsを試してみる。
勉強のためにListのAPIはなるべく使わない方向。

// P21 (*) Insert an element at a given position into a list.
// Example:
// scala> insertAt('new, 1, List('a, 'b, 'c, 'd))
// res0: List[Symbol] = List('a, 'new, 'b, 'c, 'd)

def insertAt[T](e :T, n: Int, xs: List[T]) = {
  def r(n: Int, rest: List[T], acc: List[T]): List[T] = (n, rest) match {
    case (0, h :: t) => acc.reverse ::: List(e) ::: rest
    case (_, h :: t) => r(n - 1, t, h :: acc)
  }
  if(n < 0 || xs.size <= n) throw new NoSuchElementException else r(n, xs, Nil)
}

def insertAt2[T](e :T, n: Int, xs: List[T]) = {
  if(n < 0 || xs.size <= n) throw new NoSuchElementException
  val splitted = xs.splitAt(n)
  splitted._1 ::: List(e) :::  splitted._2
}
解答例
君、それ好きだよね。

No comments:

Post a Comment