Created
December 30, 2020 00:03
-
-
Save Slakah/3030305fef94f65d6f1cbae8be4d5df7 to your computer and use it in GitHub Desktop.
.slidingN, Scala .sliding method, but for tuples. Only relies on foldable, could do up to .sliding22
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import $ivy.`org.typelevel::cats-core:2.3.0` | |
import cats.data.NonEmptyList | |
import cats.Foldable | |
import cats.implicits._ | |
def sliding2[F[_] : Foldable, A](l: F[A]): Option[NonEmptyList[(A, A)]] = { | |
l.foldLeft[(List[(A, A)], Option[A])]((Nil, None)) { | |
case ((acc, Some(x1)), x2) => | |
((x1, x2) :: acc, Some(x2)) | |
case ((Nil, None), x) => | |
(Nil, Some(x)) | |
}._1.reverse.toNel | |
} | |
sliding2(1 to 1).toList) // : None | |
sliding2((1 to 5).toList).get.toList // : List((1, 2), (2, 3), (3, 4), (4, 5)) | |
def sliding3[F[_] : Foldable, A](l: F[A]): Option[NonEmptyList[(A, A, A)]] = { | |
l.foldLeft[(List[(A, A, A)], List[A])]((Nil, Nil)) { | |
case ((acc, x2 :: x1 :: Nil), x3) => | |
((x1, x2, x3) :: acc, x3 :: x2 :: Nil) | |
case ((Nil, l), x) => | |
(Nil, x :: l) | |
}._1.reverse.toNel | |
} | |
sliding3((1 to 2).toList) // : None | |
sliding3((1 to 5).toList).get // : List((1, 2, 3), (2, 3, 4), (3, 4, 5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment