Insert an element between each two adjacent elements of Seq
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)
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 Seq
s too.