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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With