Skip to content

Instantly share code, notes, and snippets.

@frankandrobot
Created March 26, 2015 04:17
Show Gist options
  • Save frankandrobot/ad857698f680aceb44e8 to your computer and use it in GitHub Desktop.
Save frankandrobot/ad857698f680aceb44e8 to your computer and use it in GitHub Desktop.
Playground showing complex async transforms
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
case class Tag(name:String = "0")
object HelloWorld {
def fetchAllTags:Future[List[Tag]] = Future{ List(Tag("a"), Tag("b"), Tag("c")) }
def findCombinedNearestNeighbors(targets:List[Tag], alltags:List[Tag]): Future[List[Tag]] = {
//the real algorithm would do stuff with both targets and alltags
val run_algorithm = (target:Tag) => Future.successful(List(Tag("x"), Tag("y"), Tag("z")))
//merge nearest neighbors into single list
//(real algorithm would remove duplicates)
val result = Future.sequence(targets.map(run_algorithm))
result.map(result => result.flatten)
}
def findSSA(allnearestneighbors:List[Tag], alltags:List[Tag]): Future[Map[Tag, List[Int]]] = {
//real algorithm would do stuff with both neighbors and alltags
val run_algorithm = (neighbor: Tag) => Future.successful {
Map(neighbor -> List(0, 1, 2, 3, 4, 5))
}
//return combined map
Future.traverse(allnearestneighbors)(run_algorithm).map { list_of_maps =>
list_of_maps.reduce(_ ++ _)
}
}
def preprocess1(targets:List[Tag]):Future[Map[Tag, List[Int]]] = {
fetchAllTags.flatMap { alltags =>
findCombinedNearestNeighbors(targets, alltags)
.flatMap { allneighbors => findSSA(allneighbors, alltags)}
}
}
def preprocess2(targets:List[Tag]):Future[Map[Tag, List[Int]]] = {
for {
alltags <- fetchAllTags
allneighbors <- findCombinedNearestNeighbors(targets, alltags)
ssa <- findSSA(allneighbors, alltags)
}
yield {
ssa
}
}
def main(args:Array[String]) = {
//var print = (rslt:List[Tag]) => println(rslt)
fetchAllTags.onSuccess{
case rslt => println(rslt);
}
findCombinedNearestNeighbors(List(Tag(), Tag()), List(Tag())).onSuccess{
case rslt => println(rslt);
}
findSSA(List(Tag(), Tag()), List(Tag())).onSuccess {
case rslt => println(rslt)
}
preprocess1(List(Tag(),Tag(),Tag())).onSuccess( {
case rslt => println(s"preprocess1: $rslt")
})
preprocess2(List(Tag(),Tag(),Tag())).onSuccess( {
case rslt => println(s"preprocess2: $rslt")
})
Thread.sleep(500)
//println(preprocess4(List(Tag("1"), Tag("2"))))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment