Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Scala 101: Algebraic Data Types and Typeclasses

Scala 101: Algebraic Data Types and Typeclasses

Introduction to Type theory in Scala

#scala #typetheory #type #algebraic #types #sumtypes #producttypes #typeclasses #adt

Ajay Viswanathan

May 24, 2018
Tweet

More Decks by Ajay Viswanathan

Other Decks in Programming

Transcript

  1. Traits trait Employee trait Developer extends Employee trait Manager extends

    Employee { def delegate(d: Developer): Unit = println(d) } Can be used like interfaces Can be mixed in with classes and objects Supports multiple inheritance using trait linearization
  2. Classes class Person(name: String, age: Int) extends Employee case class

    Person(name: String, age: Int) extends Employee { def hashCode(): Int = name.map(c => c.toInt).sum } Functions def printPerson(p: Person): Unit = { println(p.name, p.age) } def generateId(p: Person): Int = p.hashCode()
  3. Objects object HelloWorld extends App { println("Hello World") } case

    class Country(name: String) object Country { val codes: Map[Int, String] = ??? def apply(code: Int) = Country(codes(code)) def printCountry(c: Country) = println(c) } object CountryKeys extends Enumeration { val IN, US = Value val UK = Value("uk") }
  4. The tools we use have a profound (and devious!) in

    uence on our thinking habits, and, therefore, on our thinking abilities -- Edsger Dijkstra, How do we tell truths that might hurt? “ “ Don't you hate code that's not properly indented? Making it part of the syntax guarantees that all code is properly indented! -- Guido van Rossum “ “
  5. Types type Distance = Double type Weight = Double def

    addWeightWithoutTypes(a: Double, b: Double) = ??? def addWeightWithTypes(a: Weight, b: Weight) = ??? val (d1: Double, w1: Double) = (2.2, 87) // (distance, weight) val (d2: Distance, w2: Weight) = (2.2, 87) // weight addWeightWithoutTypes(d, w) // compiles and runs but is incorrect behavior addWeightWithTypes(d, w) // compile time error preventing incorrect usage Catches bugs at compile time Readable code
  6. Product types This and That type Person = (String, Int)

    case class Person(name: String, age: Int) Every domain class can be considered a Product type Typically is the type that is passed around to functions
  7. Sum types This or That sealed trait Direction case object

    North extends Direction case object East extends Direction case object West extends Direction case object South extends Direction De nes a base type that can refer to any of its implementations Typically functions would take elements of base type as argument and gure out underlying implementation inside it
  8. Algebraic Data Type sealed trait Tree[T] case class Leaf[T](v: T)

    extends Tree[T] case class Node[T](l: Tree[T], r: Tree[T]) extends Tree[T] Can be thought of as a combination of Product and Sum types Can de ne bounds and ensure typesafety for generic inputs
  9. Typeclasses An interface that de nes behavior Takes a type

    as an argument Not the same as extending an interface
  10. Example trait MakesNoise[T] { def makeNoise(t: T): String } case

    class Car { def horn() = "beep beep" } case class Dog { def bark() = "bow bow" }
  11. Example object Implicits { implicit val carNoise = new MakesNoise[Car]

    { def makeNoise(t: Car) = t.horn() } implicit val dogNoise = new MakesNoise[Dog] { def makeNoise(t: Dog) = t.bark() } } object KickNoisyObject { import Implicits._ def kickObject[T](t: T)(implicit makesNoise: MakesNoise[T]): String = { makesNoise.makeNoise(t) } }
  12. Demo Problem Statement Build a DSL for a basic calculator

    Can parse and evaluate input like 3 plus 4 into 7 Use ADTs for optimizations and other functions Source code of demo project
  13. Give someone a program, you frustrate them for a day;

    teach them how to program, you frustrate them for a lifetime -- David Leinweber, Nerds of Wall Street “ “
  14. For further reading 1. Scala School by Twitter - Good

    starting point to get familiar with the syntax 2. Scala Exercises - Practise and learn Scala 3. Scala Levels - Conceptual milestones postulated by Martin Odersky 4. Learn you a Haskell for Great Good! - The most fun resource for indepth understanding of functional programming 5. Functional Programming in Scala - If you're someone who prefers a structured way of learning 6. Scala Cookbook - Highly useful if you want to get shit done in scala
  15. References 1. Algebraic Data Type 2. Sum vs Product types

    in Scala 3. Functional programming with Typeclasses 4. cats - a modular and extensible library for functional programming 5. Uncle Bob's Bowling Game Kata 6. Publishing an SBT project to Bintray 7. Marp, Markdown PPT editor 8. Source code of demo project