2

How to combine two List of different sizes ?

For example merge(List("a", "b"), List("1", "2", "3"), "") should return List(("a, "1"), ("b", "2"), ("", "3"))

Here is my current version :

def merge[A](l1: List[A], l2: List[A], default: A) : List[(A, A)] = {
    val m = max(l1.size, l2.size)
    l1.padTo(m, default).zip(l2.padTo(m, default))
}

Is there a better way ?

Yann Moisan
  • 8,161
  • 8
  • 47
  • 91
  • I think your version is fine, but if you want some other ideas, [here](http://stackoverflow.com/q/3015962/334519)'s a related Haskell question I asked a long time ago. – Travis Brown Feb 24 '16 at 23:25
  • @EndeNeu my question is for generic `List` and not only `List[String]`. Moreover, I don't mix two concerns : merging the list and combining elements in resulting tuples. – Yann Moisan Feb 25 '16 at 00:18
  • @YannMoisan you want the same output basically which is a list of tuples with a default for the shorter list, the fact that you want it to be for a generic type doesn't make your question different than that one in my opinion, plus you already know how to do it with generics, in your merge method you also ask for a `default: A` parameter which can be used in `zipAll`. – Ende Neu Feb 25 '16 at 08:20

1 Answers1

3

zipAll does exactly what you need:

def merge[A](l1: List[A], l2: List[A], default: A) : List[(A, A)] = {
  l1.zipAll(l2, default, default)
}
Giovanni Caporaletti
  • 5,426
  • 2
  • 26
  • 39