Skip to content

Instantly share code, notes, and snippets.

@macalinao
Created May 15, 2017 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macalinao/a8b3a1578cf52cec366fa5368bb4b2a5 to your computer and use it in GitHub Desktop.
Save macalinao/a8b3a1578cf52cec366fa5368bb4b2a5 to your computer and use it in GitHub Desktop.
package io.asuna.cantor.model
import cats._, implicits._
import monix.eval.Task
import monix.cats._
/**
* A model that supports writes.
*/
trait Sink[K, V] {
/**
* Writes the given map of keys to values.
*/
def writeMany(els: Map[K, V]): Task[Unit]
/**
* Clears the keys in the sink. Usually deletion.
*/
def clear(keys: List[K]): Task[Unit]
}
object Sink extends SinkInstances
private[model] sealed trait SinkInstances {
/**
* `Apply` instance for `Source`. Allows us to take products of sources.
*/
implicit def cvcartesianInstance[K, V]: ContravariantCartesian[Sink[K, ?]] = new ContravariantCartesian[Sink[K, ?]] {
def contramap[A, B](fa: Sink[K, A])(fn: B => A): Sink[K, B] = new Sink[K, B] {
override def writeMany(els: Map[K, B]): Task[Unit] = fa.writeMany(els.mapValues(fn))
override def clear(keys: List[K]): Task[Unit] = fa.clear(keys)
}
def product[A, B](fa: Sink[K, A], fb: Sink[K, B]): Sink[K, (A, B)] = new Sink[K, (A, B)] {
override def writeMany(els: Map[K, (A, B)]): Task[Unit] =
fa.writeMany(els.mapValues(_._1))
.product(fb.writeMany(els.mapValues(_._2))).map(_ => ())
override def clear(keys: List[K]): Task[Unit] =
fa.clear(keys).product(fa.clear(keys)).map(_ => ())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment