勉強のためにListのAPIはなるべく使わない方向で。
// P14 (*) Duplicate the elements of a list. // Example: // scala> duplicate(List('a, 'b, 'c, 'c, 'd)) // res0: List[Symbol] = List('a, 'a, 'b, 'b, 'c, 'c, 'c, 'c, 'd, 'd) def duplicate[T](xs: List[T]): List[T] = xs match { case h :: t => h :: h :: duplicate(t) case Nil => xs } def duplicate_tail[T](xs: List[T]) = { def recursive(ys: List[T], acc: List[T]): List[T] = ys match { case Nil => acc case h :: t => recursive(t, h :: h :: acc) } recursive(xs, Nil).reverse } def duplicate_map[T](xs: List[T]): List[T] = xs.flatMap{ x => x :: x :: Nil} //val l = List('a, 'b, 'c, 'c, 'd) val l = 1 to 1000000 toList println(duplicate_tail(l)) println(duplicate_map(l)) println(duplicate(l)) // StackOverFlow
解答例
そうですよね。
No comments:
Post a Comment