• API
• FAQ
• Tools
• Archive
daily pastebin goal
24%
SHARE
TWEET

# Untitled

a guest Mar 23rd, 2019 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import scala.collection.{mutable, _}
2.
3. final class Alternating[Even, Odd] private(val first: Even, val rest: Seq[(Odd, Even)])
4.   extends immutable.Iterable[Either[Even, Odd]] {
5.   self =>
6.
7.   def this(firstElement: Even) = this(firstElement, Seq())
8.
9.   def appended[E >: Even, O >: Odd](elem: (O, E)): Alternating[E, O] =
10.     new Alternating[E, O](first, rest :+ elem)
11.
12.   def prepended[E >: Even, O >: Odd](elem: (E, O)): Alternating[E, O] =
13.     new Alternating[E, O](elem._1, (elem._2, first) +: rest)
14.
15.   @inline def :+[E >: Even, O >: Odd](elem: (O, E)): Alternating[E, O] = appended(elem)
16.
17.   @inline def +:[E >: Even, O >: Odd](elem: (E, O)): Alternating[E, O] = prepended(elem)
18.
19.   def apply(i: Int): Either[Even, Odd] = i match {
20.     case 0 => Left(first)
21.     case even if i % 2 == 0 => Left(rest(i / 2 - 1)._2)
22.     case odd => Right(rest(i / 2)._1)
23.   }
24.
25.   def length = rest.length * 2 + 1
26.
27.   override def iterator: Iterator[Either[Even, Odd]] = new AbstractIterator[Either[Even, Odd]] {
28.     private var current = 0
29.     override def hasNext = current < self.length
30.     override def next() = {
31.       val elem = self(current)
32.       current += 1
33.       elem
34.     }
35.   }
36.
37.   def evens: Seq[Even] = first +: rest.map { case (o, e) => e }
38.
39.   def odds: Seq[Odd] = rest.map { case (o, e) => o }
40.
41.   def evenSlide: Seq[(Option[Odd], Even, Option[Odd])] = {
42.     val someOdds = odds.map(Some.apply)
43.     (None +: someOdds, evens, someOdds :+ None).zipped.toSeq
44.   }
45.
46.   def oddSlide: Seq[(Even, Odd, Even)] = (evens.init, odds, evens.tail).zipped.toSeq
47.
48.   def slideBoth: Iterable[Either[(Option[Odd], Even, Option[Odd]), (Even, Odd, Even)]] = evenSlide interscalate oddSlide
49. }
50.
51. object CollectionUtil {
52.   implicit class IterableOps[A](val iterable: Iterable[A]) {
53.     def intersperse(other: Iterable[A]): Iterable[A] =
54.       iterable
55.         .map(List(_))
56.         .zipAll(
57.           other
58.             .map(List(_)),
59.           Nil,
60.           Nil
61.         )
62.         .flatMap(Function.tupled(_ ::: _))
63.
64.     def interscalate[B](other: Iterable[B]): Iterable[Either[A, B]] =
65.       iterable
66.         .map(Left[A, B])
67.         .map(List(_))
68.         .zipAll(
69.           other
70.             .map(Right[A, B])
71.             .map(List(_)),
72.           Nil,
73.           Nil
74.         )
75.         .flatMap(Function.tupled(_ ::: _))
76.   }
77. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top