SlideShare a Scribd company logo
High Wizardry in the Land
        of Scala
         Daniel Spiewak
Agenda

• Higher-Kinds
• Typeclasses
• Type-Level Encodings
• Continuations
Higher-Kinds


• What is a “kind system”?
Higher-Kinds


• What is a “kind system”?
• What is a “type system”?
A type system is a tractable syntactic method for
proving the absence of certain program behaviors
 by classifying phrases according to the kinds of
    values they compute. – Benjamin Pierce
val i: Int = 42
val j: Int = 21

val s: String = "foo"

val f: Int => String = { _.toString }

val xs: List[Int] = List(1, 1, 2, 3, 5, 8)
Values
Types


Values
???


Types


Values
Kinds


Types


Values
Higher-Kinds

• Type systems classify values
• Kind systems classify types
• Values are to types as types are to kinds
type Int :: *

type String :: *

type (Int => String) :: *

type List[Int] :: *
type List :: ???

type Function1 :: ???
type List :: * => *

type Function1 :: (* × *) => *
// id : Int => Int
def id(x: Int) = x

// Id :: * => *
type Id[A] = A
// id : ((Int => Int), Int) => Int
def id(f: Int => Int, x: Int) = f(x)

// Id :: ((* => *) × *) => *
type Id[A[_], B] = A[B]
val map: Map[Option[Any], List[Any]] = Map(
  Some("foo") -> List("foo", "bar", "baz"),
  Some(42)    -> List(1, 1, 2, 3, 5, 8),
  Some(true) -> List(true, false, true, true))


// ugly cast!
val xs: List[String] =
  map(Some("foo")).asInstanceOf[List[String]]

// ditto!
val ys: List[Int] =
  map(Some(42)).asInstanceOf[List[Int]]
val map: HOMap[Option, List] = HOMap[Option, List](
  Some("foo") -> List("foo", "bar", "baz"),
  Some(42)    -> List(1, 1, 2, 3, 5, 8),
  Some(true) -> List(true, false, true, true))


// blissful type safety!
val xs: List[String] = map(Some("foo"))

// ditto!
val ys: List[Int] = map(Some(42))
// HOMap :: ((* => *) × (* => *)) => *
class HOMap[K[_], V[_]](delegate: Map[K[Any], V[Any]]) {
  def apply[A](key: K[A]): V[A] =
    delegate(key.asInstanceOf[K[Any]]).asInstanceOf[V[A]]
}

object HOMap {
  def apply[K[_], V[_]](tuples: (K[Any], V[Any])*) =
    new HOMap[K, V](Map(tuples: _*))
}




                                                   (credit: Jorge Ortiz)
Higher-Kinds
• Kind systems classify types
• Values are to types as types are to kinds
• “Higher” kinds are the kinds of type
  constructors
  • Type functions
• Use any time one type is logically a function
  of another
Typeclasses

• Forget everything you know about classes
 • (it won’t help you anyway)
• Instead of “class”, think “category”
• If you’ve ever looked at Haskell…
sum(List(1, 2, 3, 4))    // => 10
sum(List(3.14, 2.72))    // => 5.86
sum(List("me", "you"))   // shouldn't compile!
trait Num[A] {
  val zero: A

    def add(x: A, y: A): A
}


def sum[A](nums: List[A])(tc: Num[A]) =
  nums.foldLeft(tc.zero)(tc.add)
object IntNum extends Num[Int] {
  val zero = 0

    def add(x: Int, y: Int) = x + y
}


object DoubleNum extends Num[Double] {
  val zero = 0d

    def add(x: Double, y: Double) = x + y
}
// works!
sum(List(1, 2, 3, 4))(IntNum)
sum(List(3.14, 2.72))(DoubleNum)
Typeclasses


• This is functional, but ugly
• We have to explicitly provide the relevant
  instance of Num[A]
Typeclasses


• This is functional, but ugly
• We have to explicitly provide the relevant
  instance of Num[A]
def sum[A](nums: Seq[A])(tc: Num[A]) =
  nums.foldLeft(tc.zero)(tc.add)
def sum[A](nums: Seq[A])(implicit tc: Num[A]) =
  nums.foldLeft(tc.zero)(tc.add)
object IntNum extends Num[Int] {
  val zero = 0

    def add(x: Int, y: Int) = x + y
}


object DoubleNum extends Num[Double] {
  val zero = 0d

    def add(x: Double, y: Double) = x + y
}
implicit object IntNum extends Num[Int] {
  val zero = 0

    def add(x: Int, y: Int) = x + y
}


implicit object DoubleNum extends Num[Double] {
  val zero = 0d

    def add(x: Double, y: Double) = x + y
}
sum(List(1, 2, 3, 4))(IntNum)
sum(List(3.14, 2.72))(DoubleNum)
sum(List(1, 2, 3, 4))
sum(List(3.14, 2.72))
Typeclasses

• Typeclasses are categories of types
• If you have a set of types with well-defined
    commonalities, think about typeclasses
• Collections in 2.8
•   Numeric in 2.8
Type-Level Encodings

• Kinds make our types into superheroes
• Typeclasses allow us to abstract over types
• How can we abuse our new-found power?
Type-Level Encodings

• Kinds make our types into superheroes
• Typeclasses allow us to abstract over types
• How can we abuse our new-found power?
• Maybe…data structures at the type level?
Type-Level Encodings

•   HList is a linked-list implemented in types

    • …and values
• Sort of like Tuple, but unbounded
import HList._

val xs = 42 :: "foo" :: 3.14 :: HNil

xs.head           // => 42: Int
xs.tail.head      // => "foo": String
val xs1 = 42 :: false :: HNil
val xs2 = "Hello" :: "World" :: HNil

val xs = xs1 ++ xs2

xs.head               // => 42: Int
xs.tail.tail.head     // => "Hello": String
object HList {
  sealed trait HList {
    type Head
    type Tail <: HList
    type Append[L <: HList] <: HList

        def head: Head
        def tail: Tail

        def ++[L <: HList](xs: L): Append[L]
    }

    // ...
}
val x: List[Int] = ...
        val y: List[Int] = ...

        x ++ y



x   1    2       3       4



y   5    6       7       8       9
val x: List[Int] = ...
        val y: List[Int] = ...

        x ++ y



x        2       3       4



y   5    6       7       8       9
val x: List[Int] = ...
        val y: List[Int] = ...

        x ++ y



x                3       4



y   5    6       7       8       9
val x: List[Int] = ...
        val y: List[Int] = ...

        x ++ y



x                        4



y   5    6       7       8       9
val x: List[Int] = ...
         val y: List[Int] = ...

         x ++ y



x’


y    5    6       7       8       9
val x: List[Int] = ...
         val y: List[Int] = ...

         x ++ y



x’                        4



y    5    6       7       8       9
val x: List[Int] = ...
         val y: List[Int] = ...

         x ++ y



x’                3       4



y    5    6       7       8       9
val x: List[Int] = ...
         val y: List[Int] = ...

         x ++ y



x’        2       3       4



y    5    6       7       8       9
val x: List[Int] = ...
         val y: List[Int] = ...

         x ++ y



x’   1    2       3       4



y    5    6       7       8       9
object HList {
  // ...

    final class HNil extends HList {
      type Head = Nothing
      type Tail = Nothing
      type Append[L <: HList] = L

        def head = error("Head of an empty HList")
        def tail = error("Tail of an empty HList")

        def ::[A](a: A) = HCons(a, this)

        def ++[L <: HList](xs: L) = xs
    }

    val HNil = new HNil
}
object HList {
  // ...

    case class HCons[A, B <: HList](head: A, tail: B)
          extends HList {

        type Head = A
        type Tail = B

        type Append[L <: HList] =
          HCons[Head, Tail#Append[L]]

        def ::[C](c: C) = HCons(c, this)

        def ++[L <: HList](xs: L) =
          head :: (tail ++ xs)
    }

    type ::[A, B <: HList] = HCons[A, B]
}
Type-Level Encodings
• What about an nth(Int) function?
Type-Level Encodings
• What about an nth(Int) function?
• Not today!
 • Church Numerals
 • λ-Calculus
Type-Level Encodings
• What about an nth(Int) function?
• Not today!
 • Church Numerals
 • λ-Calculus
• We could do a lot more
 • Just not in a 45 minute talk
Continuations

• Actually, delimited continuations
 • Very different from plain continuations!
 • Not like callcc
• Not considered harmful
 • …though they can simulate goto!
case class JumpException(i: Int)
  extends RuntimeException

val res = try {
  val i = 42
  println("before")

  throw JumpException(i)   // basically: `break`

  val j: Int = i / 2

  println("after")
  println(j + 2)
  j                // needed for type checker
} catch {
  case JumpException(i) => i
}

println("outside")
val (res, func) = {
  val i = 42
  println("before")

    (i, { j: Int =>
       println("after")
       println(j + 2)
    })
}

println("outside")
func(res / 2)
func(res / 6)
val (res, func) = reset {
  val i = 42
  println("before")

    val j = shift { (k: Int => Unit) => (i, k) }

    println("after")
    println(j + 2)
}

println("outside")
func(res / 2)
func(res / 6)
val (res, func) = reset {
  val i = 42
  println("before")

    val j = shift { (k: Int => Unit) => (i, k) }

    println("after")
    println(j + 2)
}

println("outside")
func(res / 2)
func(res / 6)
val (res, func) = reset {
  val i = 42
  println("before")

    val j = shift { (k: Int => Unit) => (i, k) }

    println("after")
    println(j + 2)
}

println("outside")
func(res / 2)
func(res / 6)
val (res, func) = reset {
  val i = 42
  println("before")

    val j = shift { (k: Int => Unit) => (i, k) }

    println("after")
    println(j + 2)
}

println("outside")
func(res / 2)
func(res / 6)
def gen() = {
  var x = 1
  var y = 1

    while (true) {
      shift { (k: Unit => Result) => Result(x, k) }
      y += x
      x = y - x
    }
}


val res = reset {
  gen()
  error("It never ends that way, too!"): Result
}

val fib: Stream[Int] = res.toStream

                                                (credit: PEP-255)
def gen() = {
  var x = 1
  var y = 1

    while (true) {
      shift { (k: Unit => Result) => Result(x, k) }
      y += x
      x = y - x
    }
}


val res = reset {
  gen()
  error("It never ends that way, too!"): Result
}

val fib: Stream[Int] = res.toStream

                                                (credit: PEP-255)
Continuations


• This is cool and all, but what’s it good for?
Continuations


• This is cool and all, but what’s it good for?
• Not as much as you would think
reset {
  for (i <- 0 to 10) {
    shift { (k: Unit => Unit) => i }
  }
}
reset {
  for (i <- 0 to 10) {
    shift { (k: Unit => Unit) => i }
  }
}
Continuations

• This is cool and all, but what’s it good for?
• Not as much as you would think
 • Nonblocking I/O
 • Multi-page wizards
• Framework support is needed
Conclusion

• Higher-Kinds          • Type Encodings
 •   Classify types      •   Are really cool!

• Typeclasses           • Continuations
 •   Categorize types    •   Powerful

                         •   ...but useless
Questions?

More Related Content

What's hot

Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
Paul Phillips
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
John De Goes
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
Alfonso Ruzafa
 
Scala Intro
Scala IntroScala Intro
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
Ruslan Shevchenko
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Sanjeev_Knoldus
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rules
Debasish Ghosh
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
Michael Galpin
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
Maxim Novak
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
Tomer Gabel
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
RamnivasLaddad
 
Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUI
Bongwon Lee
 

What's hot (20)

Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rules
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUI
 

Viewers also liked

The Eff monad, one monad to rule them all
The Eff monad, one monad to rule them allThe Eff monad, one monad to rule them all
The Eff monad, one monad to rule them all
Eric Torreborre
 
Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design PatternsNLJUG
 
Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)
Legacy Typesafe (now Lightbend)
 
Why Scala?
Why Scala?Why Scala?
Why Scala?
Alex Payne
 
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Namuk Park
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 

Viewers also liked (6)

The Eff monad, one monad to rule them all
The Eff monad, one monad to rule them allThe Eff monad, one monad to rule them all
The Eff monad, one monad to rule them all
 
Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design Patterns
 
Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)
 
Why Scala?
Why Scala?Why Scala?
Why Scala?
 
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
Functional Programming in Scala in a Nutshell: Review of Functional Programmi...
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 

Similar to High Wizardry in the Land of Scala

Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
gabalese
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
PROIDEA
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kirill Rozov
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
Werner Hofstra
 
Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritance
Alexey Raga
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
romanandreg
 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
Dr. Volkan OBAN
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
Gil Cohen
 
Python3
Python3Python3
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
ssuser442080
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
Introduction to python cheat sheet for all
Introduction to python cheat sheet for allIntroduction to python cheat sheet for all
Introduction to python cheat sheet for all
shwetakushwaha45
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil Remeniuk
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
yassminkhaldi1
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
Knoldus Inc.
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
UC San Diego
 

Similar to High Wizardry in the Land of Scala (20)

Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritance
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
Python3
Python3Python3
Python3
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Introduction to python cheat sheet for all
Introduction to python cheat sheet for allIntroduction to python cheat sheet for all
Introduction to python cheat sheet for all
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Recently uploaded

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 

Recently uploaded (20)

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 

High Wizardry in the Land of Scala

  • 1. High Wizardry in the Land of Scala Daniel Spiewak
  • 2.
  • 3. Agenda • Higher-Kinds • Typeclasses • Type-Level Encodings • Continuations
  • 4. Higher-Kinds • What is a “kind system”?
  • 5. Higher-Kinds • What is a “kind system”? • What is a “type system”?
  • 6. A type system is a tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute. – Benjamin Pierce
  • 7. val i: Int = 42 val j: Int = 21 val s: String = "foo" val f: Int => String = { _.toString } val xs: List[Int] = List(1, 1, 2, 3, 5, 8)
  • 12. Higher-Kinds • Type systems classify values • Kind systems classify types • Values are to types as types are to kinds
  • 13. type Int :: * type String :: * type (Int => String) :: * type List[Int] :: *
  • 14. type List :: ??? type Function1 :: ???
  • 15. type List :: * => * type Function1 :: (* × *) => *
  • 16. // id : Int => Int def id(x: Int) = x // Id :: * => * type Id[A] = A
  • 17. // id : ((Int => Int), Int) => Int def id(f: Int => Int, x: Int) = f(x) // Id :: ((* => *) × *) => * type Id[A[_], B] = A[B]
  • 18. val map: Map[Option[Any], List[Any]] = Map( Some("foo") -> List("foo", "bar", "baz"), Some(42) -> List(1, 1, 2, 3, 5, 8), Some(true) -> List(true, false, true, true)) // ugly cast! val xs: List[String] = map(Some("foo")).asInstanceOf[List[String]] // ditto! val ys: List[Int] = map(Some(42)).asInstanceOf[List[Int]]
  • 19. val map: HOMap[Option, List] = HOMap[Option, List]( Some("foo") -> List("foo", "bar", "baz"), Some(42) -> List(1, 1, 2, 3, 5, 8), Some(true) -> List(true, false, true, true)) // blissful type safety! val xs: List[String] = map(Some("foo")) // ditto! val ys: List[Int] = map(Some(42))
  • 20. // HOMap :: ((* => *) × (* => *)) => * class HOMap[K[_], V[_]](delegate: Map[K[Any], V[Any]]) { def apply[A](key: K[A]): V[A] = delegate(key.asInstanceOf[K[Any]]).asInstanceOf[V[A]] } object HOMap { def apply[K[_], V[_]](tuples: (K[Any], V[Any])*) = new HOMap[K, V](Map(tuples: _*)) } (credit: Jorge Ortiz)
  • 21. Higher-Kinds • Kind systems classify types • Values are to types as types are to kinds • “Higher” kinds are the kinds of type constructors • Type functions • Use any time one type is logically a function of another
  • 22. Typeclasses • Forget everything you know about classes • (it won’t help you anyway) • Instead of “class”, think “category” • If you’ve ever looked at Haskell…
  • 23.
  • 24. sum(List(1, 2, 3, 4)) // => 10 sum(List(3.14, 2.72)) // => 5.86 sum(List("me", "you")) // shouldn't compile!
  • 25. trait Num[A] { val zero: A def add(x: A, y: A): A } def sum[A](nums: List[A])(tc: Num[A]) = nums.foldLeft(tc.zero)(tc.add)
  • 26. object IntNum extends Num[Int] { val zero = 0 def add(x: Int, y: Int) = x + y } object DoubleNum extends Num[Double] { val zero = 0d def add(x: Double, y: Double) = x + y }
  • 27. // works! sum(List(1, 2, 3, 4))(IntNum) sum(List(3.14, 2.72))(DoubleNum)
  • 28. Typeclasses • This is functional, but ugly • We have to explicitly provide the relevant instance of Num[A]
  • 29. Typeclasses • This is functional, but ugly • We have to explicitly provide the relevant instance of Num[A]
  • 30. def sum[A](nums: Seq[A])(tc: Num[A]) = nums.foldLeft(tc.zero)(tc.add)
  • 31. def sum[A](nums: Seq[A])(implicit tc: Num[A]) = nums.foldLeft(tc.zero)(tc.add)
  • 32. object IntNum extends Num[Int] { val zero = 0 def add(x: Int, y: Int) = x + y } object DoubleNum extends Num[Double] { val zero = 0d def add(x: Double, y: Double) = x + y }
  • 33. implicit object IntNum extends Num[Int] { val zero = 0 def add(x: Int, y: Int) = x + y } implicit object DoubleNum extends Num[Double] { val zero = 0d def add(x: Double, y: Double) = x + y }
  • 34. sum(List(1, 2, 3, 4))(IntNum) sum(List(3.14, 2.72))(DoubleNum)
  • 35. sum(List(1, 2, 3, 4)) sum(List(3.14, 2.72))
  • 36. Typeclasses • Typeclasses are categories of types • If you have a set of types with well-defined commonalities, think about typeclasses • Collections in 2.8 • Numeric in 2.8
  • 37. Type-Level Encodings • Kinds make our types into superheroes • Typeclasses allow us to abstract over types • How can we abuse our new-found power?
  • 38. Type-Level Encodings • Kinds make our types into superheroes • Typeclasses allow us to abstract over types • How can we abuse our new-found power? • Maybe…data structures at the type level?
  • 39. Type-Level Encodings • HList is a linked-list implemented in types • …and values • Sort of like Tuple, but unbounded
  • 40. import HList._ val xs = 42 :: "foo" :: 3.14 :: HNil xs.head // => 42: Int xs.tail.head // => "foo": String
  • 41. val xs1 = 42 :: false :: HNil val xs2 = "Hello" :: "World" :: HNil val xs = xs1 ++ xs2 xs.head // => 42: Int xs.tail.tail.head // => "Hello": String
  • 42. object HList { sealed trait HList { type Head type Tail <: HList type Append[L <: HList] <: HList def head: Head def tail: Tail def ++[L <: HList](xs: L): Append[L] } // ... }
  • 43. val x: List[Int] = ... val y: List[Int] = ... x ++ y x 1 2 3 4 y 5 6 7 8 9
  • 44. val x: List[Int] = ... val y: List[Int] = ... x ++ y x 2 3 4 y 5 6 7 8 9
  • 45. val x: List[Int] = ... val y: List[Int] = ... x ++ y x 3 4 y 5 6 7 8 9
  • 46. val x: List[Int] = ... val y: List[Int] = ... x ++ y x 4 y 5 6 7 8 9
  • 47. val x: List[Int] = ... val y: List[Int] = ... x ++ y x’ y 5 6 7 8 9
  • 48. val x: List[Int] = ... val y: List[Int] = ... x ++ y x’ 4 y 5 6 7 8 9
  • 49. val x: List[Int] = ... val y: List[Int] = ... x ++ y x’ 3 4 y 5 6 7 8 9
  • 50. val x: List[Int] = ... val y: List[Int] = ... x ++ y x’ 2 3 4 y 5 6 7 8 9
  • 51. val x: List[Int] = ... val y: List[Int] = ... x ++ y x’ 1 2 3 4 y 5 6 7 8 9
  • 52. object HList { // ... final class HNil extends HList { type Head = Nothing type Tail = Nothing type Append[L <: HList] = L def head = error("Head of an empty HList") def tail = error("Tail of an empty HList") def ::[A](a: A) = HCons(a, this) def ++[L <: HList](xs: L) = xs } val HNil = new HNil }
  • 53. object HList { // ... case class HCons[A, B <: HList](head: A, tail: B) extends HList { type Head = A type Tail = B type Append[L <: HList] = HCons[Head, Tail#Append[L]] def ::[C](c: C) = HCons(c, this) def ++[L <: HList](xs: L) = head :: (tail ++ xs) } type ::[A, B <: HList] = HCons[A, B] }
  • 54. Type-Level Encodings • What about an nth(Int) function?
  • 55. Type-Level Encodings • What about an nth(Int) function? • Not today! • Church Numerals • λ-Calculus
  • 56. Type-Level Encodings • What about an nth(Int) function? • Not today! • Church Numerals • λ-Calculus • We could do a lot more • Just not in a 45 minute talk
  • 57. Continuations • Actually, delimited continuations • Very different from plain continuations! • Not like callcc • Not considered harmful • …though they can simulate goto!
  • 58. case class JumpException(i: Int) extends RuntimeException val res = try { val i = 42 println("before") throw JumpException(i) // basically: `break` val j: Int = i / 2 println("after") println(j + 2) j // needed for type checker } catch { case JumpException(i) => i } println("outside")
  • 59. val (res, func) = { val i = 42 println("before") (i, { j: Int => println("after") println(j + 2) }) } println("outside") func(res / 2) func(res / 6)
  • 60. val (res, func) = reset { val i = 42 println("before") val j = shift { (k: Int => Unit) => (i, k) } println("after") println(j + 2) } println("outside") func(res / 2) func(res / 6)
  • 61. val (res, func) = reset { val i = 42 println("before") val j = shift { (k: Int => Unit) => (i, k) } println("after") println(j + 2) } println("outside") func(res / 2) func(res / 6)
  • 62. val (res, func) = reset { val i = 42 println("before") val j = shift { (k: Int => Unit) => (i, k) } println("after") println(j + 2) } println("outside") func(res / 2) func(res / 6)
  • 63. val (res, func) = reset { val i = 42 println("before") val j = shift { (k: Int => Unit) => (i, k) } println("after") println(j + 2) } println("outside") func(res / 2) func(res / 6)
  • 64. def gen() = { var x = 1 var y = 1 while (true) { shift { (k: Unit => Result) => Result(x, k) } y += x x = y - x } } val res = reset { gen() error("It never ends that way, too!"): Result } val fib: Stream[Int] = res.toStream (credit: PEP-255)
  • 65. def gen() = { var x = 1 var y = 1 while (true) { shift { (k: Unit => Result) => Result(x, k) } y += x x = y - x } } val res = reset { gen() error("It never ends that way, too!"): Result } val fib: Stream[Int] = res.toStream (credit: PEP-255)
  • 66. Continuations • This is cool and all, but what’s it good for?
  • 67. Continuations • This is cool and all, but what’s it good for? • Not as much as you would think
  • 68. reset { for (i <- 0 to 10) { shift { (k: Unit => Unit) => i } } }
  • 69. reset { for (i <- 0 to 10) { shift { (k: Unit => Unit) => i } } }
  • 70. Continuations • This is cool and all, but what’s it good for? • Not as much as you would think • Nonblocking I/O • Multi-page wizards • Framework support is needed
  • 71. Conclusion • Higher-Kinds • Type Encodings • Classify types • Are really cool! • Typeclasses • Continuations • Categorize types • Powerful • ...but useless

Editor's Notes