Skip to content

Instantly share code, notes, and snippets.

@vasigorc
Last active November 15, 2021 22:00
Show Gist options
  • Save vasigorc/9ed3f3d5ecd985f6132a65ef8cbba47c to your computer and use it in GitHub Desktop.
Save vasigorc/9ed3f3d5ecd985f6132a65ef8cbba47c to your computer and use it in GitHub Desktop.
How an Array Monad could look like (naÏve approach)
import cats.Monad
import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
object CatsUtil {
implicit val arrayMonad: Monad[Array] = new Monad[Array] {
override def flatMap[A, B](fa: Array[A])(f: A => Array[B]): Array[B] = {
if (fa.isEmpty) return Array.empty
val buffer = ArrayBuffer.empty[B]
val iterator: Iterator[A] = fa.iterator
while (iterator.hasNext) {
val nextValue: A = iterator.next()
f(nextValue).foreach(buffer.addOne)
}
buffer.toArray
}
@tailrec
override def tailRecM[A, B](a: A)(f: A => Array[Either[A, B]]): Array[B] = f(a) match {
case Array(Left(a1)) => tailRecM(a1)(f)
case Array(Right(b1)) => pure(b1)
}
override def pure[A](a: A): Array[A] = Array(a)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment