Skip to content

Instantly share code, notes, and snippets.

@kailuowang
Created January 1, 2016 02:18
Show Gist options
  • Save kailuowang/9fe6cc2559f1c830c909 to your computer and use it in GitHub Desktop.
Save kailuowang/9fe6cc2559f1c830c909 to your computer and use it in GitHub Desktop.
Processor Data Structure
object Test {
type Cause = String
type FutureXor[A] = XorT[Future, Cause, A]
case class ProcessContext[+A](context: List[String], data: A) //context never need to change
trait Processor[-A, B] extends Serializable {
def process: ProcessContext[A] ⇒ FutureXor[B]
}
implicit class ProcessorOps[A, B](self: Processor[A, B]) {
def >>[C](that: Processor[B, C]) = Con(self, that)
def zip[C](that: Processor[A, C]) = Zip(self, that)
}
//concat two processors
case class Con[A, B, C](a: Processor[A, C], b: Processor[C, B]) extends Processor[A, B] {
def process: ProcessContext[A] ⇒ FutureXor[B] = (pc: ProcessContext[A]) ⇒
a.process(pc).flatMap { c ⇒
b.process(pc.copy(data = c))
}
}
//zip two processors
case class Zip[A, B, C](p1: Processor[A, B], p2: Processor[A, C]) extends Processor[A, (B, C)] {
def process: ProcessContext[A] ⇒ FutureXor[(B, C)] = (pc: ProcessContext[A]) ⇒
for {
b ← p1.process(pc)
c ← p2.process(pc)
} yield (b, c)
}
val a: Processor[String, Int] = ???
val b: Processor[Int, Double] = ???
val d: Processor[String, Double] = ???
val c = a >> b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment