Skip to content

Instantly share code, notes, and snippets.

@frohoff
Created May 7, 2015 20:20
Show Gist options
  • Save frohoff/db15cb9244e5a6184ab3 to your computer and use it in GitHub Desktop.
Save frohoff/db15cb9244e5a6184ab3 to your computer and use it in GitHub Desktop.
functional composition flow
object Test extends App {
lazy val flow: SplunkEvent => Seq[Email[Alert]] =
receiveEvent andTap rawTap andThen
convertToSecurityEvent andMaybeTap eventTap andMaybe
classifyIfTrained andMaybeTap classificationTap andMaybeSeq
aggregateByTimeWindow andForEach (_.sortBy(_.event.time)) andForEach
convertToAlert andForEachTap alertTap andForEachOpt
createEmail andForEachTap emailTap
}
package object flow {
implicit class RichFunction[A, B](f: Function1[A, B]) {
def andTap(g: B => Unit): Function1[A, B] = f andThen { b => g(b); b }
def sink: Function[A, Unit] = f andThen (_ => ())
def forEach: Function[Traversable[A], Traversable[B]] = t => t.map(f)
def maybe: Function[Option[A], Option[B]] = o => o.map(f)
}
implicit class RichOptionFunction[A, B](f: Function1[A, Option[B]]) {
def andMaybe[C](g: B => C): Function1[A, Option[C]] = f andThen (_.map(g))
def andMaybeFlat[C](g: B => Option[C]): Function1[A, Option[C]] = f andThen (_.flatMap(g))
def andMaybeSeq[C](g: B => Seq[C]): Function1[A, Seq[C]] = f andThen (_ map g) andThen (_ getOrElse List())
def andMaybeTap(g: B => Unit): Function1[A, Option[B]] = f andMaybe { b => g(b); b }
}
implicit class RichSeqFunction[A, B](f: Function1[A, Seq[B]]) {
def andForEach[C](g: B => C): Function1[A, Seq[C]] = f andThen (_ map g)
def andForEachFlat[C](g: B => Seq[C]): Function1[A, Seq[C]] = f andThen (_ flatMap g)
def andForEachOpt[C](g: B => Option[C]): Function1[A, Seq[C]] = f andThen (_ flatMap (g andThen (_.toSeq)))
def andForEachTap(g: B => Unit): Function1[A, Seq[B]] = f andThen (_ map (_ tap g))
}
implicit class RichUnitFunction[A](f: A => Unit) {
def andAlso(g: A => Unit): A => Unit = tap(f) andThen g
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment