Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert an element between each two adjacent elements of Seq

Tags:

scala

For example, I have Seq(1,2,3) and I want to get Seq(1,0,2,0,3)

The first thing that comes to mind is:

  scala> Seq(1,2,3).flatMap(e => 0 :: e :: Nil).tail
  res17: Seq[Int] = List(1, 0, 2, 0, 3)

Is there any better/more elegant option?

like image 561
mmmbell Avatar asked Nov 03 '12 20:11

mmmbell


2 Answers

Here is another approach:

def intersperse[E](x: E, xs:Seq[E]): Seq[E] = (x, xs) match {
    case (_, Nil)     => Nil
    case (_, Seq(x))  => Seq(x) 
    case (sep, y::ys) => y+:sep+:intersperse(sep, ys)
}

which is safe over empty Seqs too.

like image 112
Robert Avatar answered Oct 09 '22 09:10

Robert


Try for comprehension:

for(i <- list; p <- List(0, i)) yield p

However you must somehow remove the first element (it yields: 0,1,0,2,0,3), either by:

(for(i <- list; p <- List(0, i)) yield p).tail

or:

list.head :: (for(i <- list.tail; p <- List(0, i)) yield p)
like image 21
Tomasz Nurkiewicz Avatar answered Oct 09 '22 10:10

Tomasz Nurkiewicz