Skip to content

Instantly share code, notes, and snippets.

@tuxdna
Last active October 31, 2018 22:39
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tuxdna/3736240330b13353df1aa322fb14530e to your computer and use it in GitHub Desktop.
Examples: sealed families of singleton objects extending functions

Trying to understand what this means in the article below:

Finally, we use “sealed families of singleton objects extending functions” to organzse our filters, maps, and aggregations. In a nutshell, that means we can check equality on code paths as not to duplicate execution—which seemingly provides auto-magical distributed “memorization” but not via traditional AOP mechanisms.

Example run

$ bin/scala
Welcome to Scala version 2.10.6 (OpenJDK 64-Bit Server VM, Java 1.8.0_102).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

sealed trait Transformer[P, Q] {
  protected def transform(x: P): Q
  def apply(x: P): Q = transform(x)
}

object Int2StringTransformer extends Transformer[Int, String] {
  def transform(x: Int): String = x.toString
}

object List2SetTransformer extends Transformer[List[_], Set[_]] {
  def transform(x: List[_]) = x.toSet
}

object Example {
  def main(args: Array[String]) {
    println(List2SetTransformer(List(10, 11)))
  }
}

// Exiting paste mode, now interpreting.

defined trait Transformer
defined module Int2StringTransformer
defined module List2SetTransformer
defined module Example

scala> Example.main(Array())
Set(10, 11)

scala> Int2StringTransformer.transform(10)
res1: String = 10

sealed trait Transformer[P, Q] {
protected def transform(x: P): Q
def apply(x: P): Q = transform(x)
}
object Int2StringTransformer extends Transformer[Int, String] {
def transform(x: Int): String = x.toString
}
object List2SetTransformer extends Transformer[List[_], Set[_]] {
def transform(x: List[_]) = x.toSet
}
object Example {
def main(args: Array[String]) {
println(List2SetTransformer(List(10, 11)))
}
}
@leobenkel
Copy link

Is that faster ? I read the article too and was confused ? What is the gain here ? Did you run any benchmark?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment