@@ -601,6 +601,40 @@ def zip[A, B](left: List[A], right: List[B]): List[(A, B)] = {
601
601
go(Nil(), left, right)
602
602
}
603
603
604
+ /// Produce a list of OneOrBoth from two lists.
605
+ /// The length is the maximum of lenghts of the two lists.
606
+ ///
607
+ /// Examples:
608
+ /// ```
609
+ /// > zipLongest([1, 2, 3], [100, 200, 300])
610
+ /// [Both(1, 100), Both(2, 200), Both(3, 300)]
611
+ ///
612
+ /// > zipLongest([1, 2, 3], Nil[Int]())
613
+ /// [This(1), This(2), This(3)]
614
+ ///
615
+ /// > zipLongest(Nil[Int](), [1, 2, 3])
616
+ /// [That(1), That(2), That(3)]
617
+ ///
618
+ /// > zipLongest([1, 2, 3], [42])
619
+ /// [These(1, 42), This(2), This(3)]
620
+ /// ```
621
+ ///
622
+ /// O(N)
623
+ def zipLongest[A, B](left: List[A], right: List[B]): List[OneOrBoth[A, B]] = {
624
+ def go(acc: List[OneOrBoth[A, B]], left: List[A], right: List[B]): List[OneOrBoth[A,B]] = {
625
+ (left, right) match {
626
+ case (Cons(a, as), Cons(b, bs)) =>
627
+ go(Cons(Both(a, b), acc), as, bs)
628
+ case (Cons(a, as), Nil()) =>
629
+ go(Cons(This(a), acc), as, Nil())
630
+ case (Nil(), Cons(b, bs)) =>
631
+ go(Cons(That(b), acc), Nil(), bs)
632
+ case _ => acc.reverse
633
+ }
634
+ }
635
+ go(Nil(), left, right)
636
+ }
637
+
604
638
/// Combine two lists with the given function.
605
639
/// The length of the result is the minimum of lengths of the two lists.
606
640
///
0 commit comments