def merge1[T](l1: List[T], l2: List[T]): List[T] =
l1.reverse.foldLeft(l2)((acc, e) => e :: acc)
/** for large lists will throws Stackoverflow */
def merge2[T](l1: List[T], l2: List[T]): List[T] =
l1.foldRight(l2)((e, acc) => e :: acc)
def flatten[A](list: List[List[A]]): List[A] =
list.foldLeft(Nil: List[A])(merge1)
如果你想添加merge
方法List
類型,你可以寫:
implicit class ListExt[T](l: List[T]) {
def merge(l2: List[T]): List[T] = merge1(l, l2)
}
def flatten2[A](list: List[List[A]]): List[A] =
list.foldLeft(Nil: List[A])((acc, e) => acc merge e)