Showing posts with label fp. Show all posts
Showing posts with label fp. Show all posts
Thursday, 22 November 2018
Tuesday, 21 November 2017
using java lambdas as groovy closure
using java lambdas from groovy
I have a scala method that takes
java.util.function.Supplier as parameter.class TestKit(system: ActorSystem) {
def awaitCond(p: Supplier[Boolean]): Unit = tp.awaitCond(p.get)
}
syntactic sugar for Supplier functor would be
() -> ... in java, but is not compiled in groovy.def actorSystem = ActorSystem.create("actor-system")
def verifier = new TestKit(actorSystem)
verifier.awaitCond { -> return verifier.msgAvailable()}
Wednesday, 15 November 2017
scala pattern matches
collect pattern matches,
scala> val data = Map((1 -> ("prog" -> "Pink floyd")), (2 -> ("metal" -> "Architects")), (3 -> ("prog" -> "Porcupine Tree")))
data: scala.collection.immutable.Map[Int,(String, String)] = Map(1 -> (prog,Pink floyd), 2 -> (metal,Architects), 3 -> (prog,Porcupine Tree))
scala> data.collect {case (k, v) if v._1 == "prog" => v._2}
res9: scala.collection.immutable.Iterable[String] = List(Pink floyd, Porcupine Tree)
scala> data.collect {case (k, (v1, v2)) if v1 == "prog" => v2}
res10: scala.collection.immutable.Iterable[String] = List(Pink floyd, Porcupine Tree)
scala foldLeft pattern matches,
scala> val data = Map((1 -> ("prog" -> "Pink floyd")), (2 -> ("metal" -> "Architects")), (3 -> ("prog" -> "Porcupine Tree")))
data: scala.collection.immutable.Map[Int,(String, String)] = Map(1 -> (prog,Pink floyd), 2 -> (metal,Architects), 3 -> (prog,Porcupine Tree))
scala> data.foldLeft(""){case (text, (id, (genre, artist))) => text + "\n" + artist}
res17: String =
"
Pink floyd
Architects
Porcupine Tree"
Friday, 3 November 2017
collectFirst on Map of Sequence
To find a product first bought from a map of year to List of Items
scala> def firstGuitar(list: Seq[String]) = list.collectFirst { case item if item == "Guitar" => item } firstGuitar: (list: Seq[String])Option[String] scala> Map(2016 -> Seq("Cap", "Guitar", "Cap"), 2017 -> Seq("Here and now album", "Drum Kits", "Cap", "Guitar")).collectFirst { case (year, itemsBought) if firstGuitar(itemsBought).nonEmpty => (year -> firstGuitar(itemsBought))} res2: Option[(Int, Option[String])] = Some((2016,Some(Guitar))) scala> Map(2016 -> Seq("Cap", "Camera", "Cap"), 2017 -> Seq("Here and now album", "Drum Kits", "Cap", "Tshirt")).collectFirst { case (year, itemsBought) if firstGuitar(itemsBought).nonEmpty => (year -> firstGuitar(itemsBought))} res3: Option[(Int, Option[String])] = None
Subscribe to:
Posts (Atom)