Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - Combine two lists in an alternating fashion

Tags:

list

scala

How do I merge 2 lists in such a way that the resulting list contains the elements of 2 lists in alternating fashion in Scala.

Input:

val list1 = List("Mary", "a", "lamb")

val list2 = List("had", "little")

Output:

List("Mary", "had", "a", "little", "lamb")
like image 817
yAsH Avatar asked Nov 06 '13 11:11

yAsH


1 Answers

What you're looking for is usually called "intersperse" or "intercalate" and there are a few ways to do it:

def intersperse[A](a : List[A], b : List[A]): List[A] = a match {
  case first :: rest => first :: intersperse(b, rest)
  case _             => b
}

You can also use scalaz

import scalaz._
import Scalaz._

val lst1 = ...
val lst2 = ...

lst1 intercalate lst2

Edit: You can also do the following:

lst1.zipAll(lst2,"","") flatMap { case (a, b) => Seq(a, b) }

Come to think of it, I believe the last solution is my favorite since it's most concise while still being clear. If you're already using Scalaz, I'd use the second solution. The first is also very readable however.

And just to make this answer more complete, adding @Travis Brown's solution that is generic:

list1.map(List(_)).zipAll(list2.map(List(_)), Nil, Nil).flatMap(Function.tupled(_ ::: _))
like image 146
yan Avatar answered Oct 14 '22 13:10

yan