Programming With Scala Types

Gregg Hernandez <gregg@lucidchart.com>

golucid.co

Church Encoding

Church Encoding

Assume Zero and a "successor" function

z = 0
1 = s(z)
2 = s(1) = s(s(z))
3 = s(2) = s(s(s(z)))
etc....

Church Encoding

Addition

a + 0 = a
a + s(b) = s(a + b)

a + 1 = a + s(0) = s(a + 0) = s(a)
a + 2 = a + s(1) = s(a + 1) = s(s(a))

implicit

Implicit Classes

implicit class ExtendedInt(val int: Int) {

  def triple: Int = int * 3

}

10.triple // 30

Implicit Parameters

def f(implicit x: Int) = x

implicit val y = 10

f // 10

Implicit Parameters

def f(implicit x: Int) = x

implicit def y = 10

f // 10

Implicit Parameters

def f(implicit x: Int) = x

implicit def y(implicit z: String) = 10

f // ???

Implicit Parameters

def f(implicit x: Int) = x

implicit def y(implicit z: String) = 10

f // could not find implicit value for parameter x

Implicit Parameters

def f(implicit x: Int) = x

implicit def y(implicit z: String) = 10

implicit val q = "hello"

f // 10

Implicit Parameters

def f(implicit x: Int) = x

implicit def y(implicit z: String) = 10

implicit val q = "hello"

f(???)

Implicit Parameters

def f(implicit x: Int) = x

implicit def y(implicit z: String) = 10

implicit val q = "hello"

f(y(???))

Implicit Parameters

def f(implicit x: Int) = x

implicit def y(implicit z: String) = 10

implicit val q = "hello"

f(y(q)) // 10

HList

HList

val list = List(
    1, 
    "hello", 
    new java.net.URL("http://world"))

list: List[?] = List(1, hello, http://world)

HList

val list = List(
    1, 
    "hello", 
    new java.net.URL("http://world"))

list: List[Any] = List(1, hello, http://world)

HList

val list = 
  1 :: "hello" :: new URL("http://world") :: HNil

val i: Int = list.at[_0]
val s: String = list.at[_1]
val u: URL = list.at[_2]

Coproduct

Coproduct

val data: Either[String, Int] = Right(10)

Coproduct

val data: scalaz.Either3[String, Int, Boolean] = 
  Either3.middle3(10)

Coproduct

val data: String :+: Int :+: Boolean :+: CNil =
  Coproduct[String :+: Int :+: Boolean :+: CNil](10)

Coproduct

type CP = String :+: Int :+: Boolean :+: CNil
val data: CP = Coproduct[CP](10)

Coproduct

type CP = String :+: Int :+: Boolean :+: CNil
val data: CP = Coproduct[CP](10)

val str: Option[String] = data.select[String] // None
val int: Option[Int] = data.select[Int] // Some(10)
val bool: Option[Boolean] = data.select[Boolean] // None

Other Features

  • iteration
  • conversion to/from HList <=> tuple
  • HList: covariance
  • unify (least upper bound)
  • Singleton types
  • Polymorphic functions

Go learn more

The Type Astronauts Guide to Shapeless

github.com/underscoreio/shapeless-guide

 

Shapeless

https://github.com/milessabin/shapeless

golucid.co

Programming With Scala Types

By Gregg H

Programming With Scala Types

  • 1,155