Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Safe sliding in Scala
trait TypedSlide[F[_], I <: Int] {
type Out[A]
def sliding[A](fa: F[A]): F[Out[A]]
object TypedSlide {
type Arbitrary
class Helper[F[_], I <: Int] {
def apply[OOut[_]](f: F[Arbitrary] => F[OOut[Arbitrary]]) = new TypedSlide[F, I] {
type Out[A] = OOut[A]
def sliding[A](fa: F[A]): F[Out[A]] = f.asInstanceOf[F[A] => F[OOut[A]]](fa)
def instance[F[_], I <: Int] = new Helper[F, I]
implicit val list2 = instance[List, 2](_.sliding(2).map { case List(a, b) => (a, b) }.toList)
implicit val list3 = instance[List, 3](_.sliding(3).map { case List(a, b, c) => (a, b, c) }.toList)
implicit val list4 = instance[List, 4](_.sliding(4).map { case List(a, b, c, d) => (a, b, c, d) }.toList)
implicit class SafeSliding[F[_], A](private val fa: F[A]) extends AnyVal {
def sliding_[I <: Int](implicit ts: TypedSlide[F, I]): F[ts.Out[A]] = ts.sliding(fa)
println("test 2")
println("test 3")
println("test 4")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment