How to merge two lists of tuples?

前端 未结 3 1538
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 12:06

I have two lists in Scala, how to merge them such that the tuples are grouped together?

Is there an existing Scala list API which can do this or need I do it by myse

3条回答
  •  别那么骄傲
    2020-12-31 12:41

    If you can assume that both List[(A,B)] are ordered according to Ordering[A], you could write something like:

    def mergeLists[A,B](one:List[(A,B)], two:List[(A,B)])(op:(B,B)=>B)(implicit ord:Ordering[A]): List[(A,B)] = (one,two) match {
        case (xs, Nil) => xs
        case (Nil, ys) => ys
        case((a,b)::xs,(aa,bb)::ys) =>
          if (a == aa) (a, op(b,bb)) :: mergeLists(xs,ys)(op)(ord)
          else if (ord.lt(a,aa)) (a, b) :: mergeLists(xs, (aa,bb)::ys)(op)(ord)
          else (aa, bb) :: mergeLists((a,b) :: xs, ys)(op)(ord)
    }
    

    Unfortunately this isn't tail recursive.

提交回复
热议问题