Skip to content

Instantly share code, notes, and snippets.

@markhibberd
Created February 15, 2013 01:15
Show Gist options
  • Select an option

  • Save markhibberd/4957915 to your computer and use it in GitHub Desktop.

Select an option

Save markhibberd/4957915 to your computer and use it in GitHub Desktop.
Applicative for Chunk[A] (A \/ StreamT[Future, A])
import scala.concurrent.{Future, ExecutionContext}
import scalaz._, Scalaz._
object Chunk {
type Chunk[A] = A \/ StreamT[Future, A]
implicit def ApplicativeChunk: Applicative[Chunk] = new Applicative[Chunk] {
def point[A](a: => A) = a.left
override def map[A, B](fa: Chunk[A])(f: A => B): Chunk[B] =
fa match {
case -\/(a) => f(a).left
case \/-(s) => (s map f).right
}
def ap[A, B](fa: => Chunk[A])(ff: => Chunk[A => B]): Chunk[B] =
fa match {
case -\/(a) => ff match {
case -\/(f) => f(a).left
case \/-(s) => s.map(f => f(a)).right
}
case \/-(as) => ff match {
case -\/(f) => as.map(a => f(a)).right
case \/-(s) => as.flatMap(a => s.map(f => f(a))).right
}
}
}
// Not sure what Future you meant, but I assume you can have an applicative for it...
implicit def Bletch: ExecutionContext = sys.error("Use a better future!")
implicit def FutureApplicative(implicit ctx: ExecutionContext): Applicative[Future] = new Applicative[Future] {
def point[A](a: => A) = Future(a)(ctx)
override def map[A, B](fa: Future[A])(f: A => B): Future[B] =
fa.map(f)(ctx)
def ap[A, B](fa: => Future[A])(f: => Future[A => B]): Future[B] =
fa.zip(f).map({case (a, f) => f(a)})(ctx)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment