def lift[A](a: Iterable[A]) = a map {Option.apply}
def unequalZip[A, B](a: Iterable[A], b: Iterable[B]) = lift(a).zipAll(lift(b), None, None)
Zipping unequal length lists in scala
-
30-06-2023 - |
Frage
I want something like this:
def unequalZip[A, B](a: Iterable[A], b: Iterable[B]) = Iterable[(Option[A], Option[B])]
where the items from the shorter iterable is matched with items from longer iterable using None
s
Lösung 2
Andere Tipps
You want
a.zipAll(b, None, None)
if you already have options, or
a.map(x => Option(x)).zipAll(b.map(x => Option(x)), None, None)
otherwise.
Take a look at zipAll.
/** Returns a $coll formed from this $coll and another iterable collection * by combining corresponding elements in pairs. * If one of the two collections is shorter than the other, * placeholder elements are used to extend the shorter collection to the length of the longer.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow