SlideShare a Scribd company logo
TOWARDS
RELIABLE LOOKUPS
Scala by the Bay 2015, August 14th
Patrick Prémont - @ppremont
Functional Programming Architect
MAP LOOKUPS
trait Map[K, V]{

def get(key: K): Option[V]

}
OPTION.GET
DEFENSIVE
PROGRAMMING
.getOrElse(

// Not sure how this

// can ever happen,

// but just in case…

“Unknown”

)()
INVALID REFERENCES
Incorrect judgements yield waste or bugs!
Impossible: Ignore/terminate
Possible:
Handle appropriately or

revise program
?
INVALID REFERENCES
WITH TOTAL-MAP
Impossible: Types prove it!
?
RELATIONAL DATABASES
Foreign Key
quantity partId
10 102
100 102
25 101
id name
101 Monitor
102 Keyboard
Shipment Part
Brittle insertion Brittle removal
@ppremont
CURRENT PRACTICE
case class Data(

parts: Map[Int, String],

shipments: List[(Int, Int)])
@ppremont
DISTINCT IDTYPES
case class PartId(id: Int)



case class Data(

parts: Map[PartId, String],

shipments: List[(Int, PartId)])
TOTAL MAPS
trait Map[K, V]{

def get(key: K): Option[V]

}



trait Total[V]{

type Id

def apply(id: Id): V

}
PATH-DEPENDENT TYPE
trait Data {

val parts: Total[String]

val shipments: List[(Int, parts.Id)]

}
SAFER UPDATES TOO
trait Total[V]{

type Id

def update(id: Id, f: V=>V)

}
IDENTIFIER TYPES
• As we insert, need types with more values
• As we remove, need types with fewer values
INSERTION
def insert(value: V): {

val total:

Total[V] {

type Id >: Total.this.Id

}

val newId: total.Id

}
REMOVAL
def remove(removedKey: Id): {

val total:

Total[V] {

type Id <: Total.this.Id

}



def filter(k: Total.this.Id): 

Option[total.Id]

}
COVARIANT
ID TYPE PARAMETERS
case class Shipment[+P](

quantity: Int,

part: P)
val parts: Total[String]
val shipments:

List[Shipment[parts.Id]]
MULTIPLE CONSTRAINTS
case class Country(name: String)

case class Address[+CountryId](country: CountryId)

case class Customer[+AddressId](address: AddressId)



trait Data {

val countries : Total[Country]

val addresses : Total[Address[countries.Id]]

val customers : List[Customer[addresses.Id]]

}
CYCLICAL CONSTRAINTS
case class User[+U](

name: String, 

follows: List[U])



trait Data {

val users : Total[User[users.Id]]

}
BREAKING THE CYCLE
case class User[+U](

name: String, 

follows: List[U])



trait Data {

val userSet : Total[Unit]

val users : userSet.Map[User[userSet.Id]]

}
COMPLEMENT TYPES
trait Total {

type Id

type Comp

def allocate: Comp

def insertAt(id: Comp) : Total {

type Id >: Total.this.Id

}

}
ID TYPE FAMILY
Nothing {}
Option[Nothing] {None}
Option[
Option[Nothing]]
{None,

Some(None)}
Option[
Option[
Option[Nothing]]]
{None,

Some(None),

Some(Some(None))}
SELECTIVE SUBSETS
Nothing {}
Either[Unit,

Nothing]
{Left(())}
Either[Unit,

Either[Unit,
Nothing]]
{Left(()),

Right(Left(()))}
Either[Nothing,

Either[Unit,
Nothing]]
{Right(Left(()))}
BINARY TREE
Nothing {}
Id2[Unit,

Nothing,

Nothing]
{Element}
Id2[Unit,

Id2[Unit,Nothing,Nothing], 

Nothing]
{Element,

Left(Element)}
Id2[Unit,

Id2[Unit,Nothing,Nothing], 

Id2[Unit,Nothing,Nothing]]
{Element,

Left(Element),

Right(Element)}
CONSTANT SPACE
Nothing {}
Id2[Unit,

Nothing,

Nothing]
{Id2(0)}
Id2[Unit,

Id2[Unit,Nothing,Nothing], 

Nothing]
{Id2(0),

Id2(1)}
Id2[Unit,

Id2[Unit,Nothing,Nothing], 

Id2[Unit,Nothing,Nothing]]
{Id2(0),

Id2(1),

Id2(2)}
PERFORMANCE
• Total maps are binary trees: O(log n) operations
• No rebalancing: identifiers designate fixed paths
to a node
• n is the highest index in use
PERFORMANCE
DEGRADATION
Total.empty

.insertAll(0 to size)
(1 to size)

.map(i => (i, i))(breakOut)

: Map[Int, Int]
us per inserted element
0
0.5
1
1.5
100 000 1 000 000
Total Map
BENEFITS
• Safe lookups, updates, inserts and removals
• Descriptive identifier types (parts.Id)
LIMITATIONS
• Traversal on removal
• Narrowing identifier types generates garbage
• Advanced, path-dependent types
• Type inference
ORTHOGONAL
PERSISTENCE
• Run a non-persistent program in a persistent
manner.
• Referential integrity must be built into the
program
TRANSACTIONS
type Txn = Data => (Data, A)
def run(txn: Txn) : IO[A] = IO{

val in = db.read[Data] 

val (out, a) = txn(in)

db.write(out)

a

}

TOTAL MAP LIBRARY
github.com/boldradius/total-map
TOWARDS
RELIABLE LOOKUPS
Scala Symposium 2015 Paper:

Referential Integrity with Scala Types
github.com/boldradius/total-map
Patrick Prémont - @ppremont

More Related Content

What's hot (20)

PDF
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
PDF
Functional programming in kotlin with Arrow [Sunnytech 2018]
Emmanuel Nhan
 
PDF
Why functional why scala
Neville Li
 
PPTX
function in c
subam3
 
PDF
Hive function-cheat-sheet
Dr. Volkan OBAN
 
PPTX
Lambda expressions
Yuriy Seniuk
 
PDF
Bcsl 033 data and file structures lab s3-1
Dr. Loganathan R
 
PDF
Cocoaheads Meetup / Alex Zimin / Swift magic
Badoo Development
 
PDF
Bcsl 033 data and file structures lab s3-3
Dr. Loganathan R
 
PDF
Function, Class
Hirakawa Akira
 
PDF
Fluent14
Brendan Eich
 
PDF
Gdg almaty. Функциональное программирование в Java 8
Madina Kamzina
 
PPTX
Optional in Java 8
Richard Walker
 
KEY
Scala implicits
nkpart
 
PPT
Qno 3 (a)
Praveen M Jigajinni
 
PDF
Functor, Apply, Applicative And Monad
Oliver Daff
 
PPT
Qno 2 (c)
Praveen M Jigajinni
 
PDF
Why functional programming and category theory strongly matters
Piotr Paradziński
 
PPTX
2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
AAKASH KUMAR
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
Functional programming in kotlin with Arrow [Sunnytech 2018]
Emmanuel Nhan
 
Why functional why scala
Neville Li
 
function in c
subam3
 
Hive function-cheat-sheet
Dr. Volkan OBAN
 
Lambda expressions
Yuriy Seniuk
 
Bcsl 033 data and file structures lab s3-1
Dr. Loganathan R
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Badoo Development
 
Bcsl 033 data and file structures lab s3-3
Dr. Loganathan R
 
Function, Class
Hirakawa Akira
 
Fluent14
Brendan Eich
 
Gdg almaty. Функциональное программирование в Java 8
Madina Kamzina
 
Optional in Java 8
Richard Walker
 
Scala implicits
nkpart
 
Functor, Apply, Applicative And Monad
Oliver Daff
 
Why functional programming and category theory strongly matters
Piotr Paradziński
 
2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
AAKASH KUMAR
 

Viewers also liked (8)

PDF
Why Not Make the Transition from Java to Scala?
BoldRadius Solutions
 
PDF
Introduction to the Typesafe Reactive Platform
BoldRadius Solutions
 
PDF
Partial Functions in Scala
BoldRadius Solutions
 
PDF
How You Convince Your Manager To Adopt Scala.js in Production
BoldRadius Solutions
 
PDF
Introduction to the Actor Model
BoldRadius Solutions
 
PDF
Akka in Practice: Designing Actor-based Applications
NLJUG
 
PDF
Zabbix 3.2 - мониторинг качественно нового уровня / Алексей Владышев (Zabbix)
Ontico
 
PPTX
SmartMonitoring - мониторинг бизнес-логики в Одноклассниках / Сергей Шарапов ...
Ontico
 
Why Not Make the Transition from Java to Scala?
BoldRadius Solutions
 
Introduction to the Typesafe Reactive Platform
BoldRadius Solutions
 
Partial Functions in Scala
BoldRadius Solutions
 
How You Convince Your Manager To Adopt Scala.js in Production
BoldRadius Solutions
 
Introduction to the Actor Model
BoldRadius Solutions
 
Akka in Practice: Designing Actor-based Applications
NLJUG
 
Zabbix 3.2 - мониторинг качественно нового уровня / Алексей Владышев (Zabbix)
Ontico
 
SmartMonitoring - мониторинг бизнес-логики в Одноклассниках / Сергей Шарапов ...
Ontico
 
Ad

Similar to Towards Reliable Lookups - Scala By The Bay (20)

PDF
Scala or functional programming from a python developer's perspective
gabalese
 
PDF
Event Sourcing and Functional Programming
GlobalLogic Ukraine
 
PDF
Functional Programming & Event Sourcing - a pair made in heaven
Pawel Szulc
 
PPTX
Scala best practices
Alexander Zaidel
 
PDF
Functional programming in Scala
Damian Jureczko
 
PPTX
Improving Correctness with Types
Iain Hull
 
PDF
Monads and Monoids by Oleksiy Dyagilev
JavaDayUA
 
PPTX
Improving Correctness With Type - Goto Con Berlin
Iain Hull
 
PDF
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
PDF
What Have The Properties Ever Done For Us
Miklós Martin
 
PDF
Scala Quick Introduction
Damian Jureczko
 
PDF
Railroading into Scala
Nehal Shah
 
PDF
Generic Functional Programming with Type Classes
Tapio Rautonen
 
PDF
Monads asking the right question
Pawel Szulc
 
PPT
Functional programming in scala
Siarhiej Siemianchuk
 
PDF
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
PDF
Scala for Java Developers (Silicon Valley Code Camp 13)
Ramnivas Laddad
 
PDF
Gentle Introduction to Scala
Fangda Wang
 
PPT
Functional programming with_scala
Raymond Tay
 
PPTX
Improving Correctness with Types Kats Conf
Iain Hull
 
Scala or functional programming from a python developer's perspective
gabalese
 
Event Sourcing and Functional Programming
GlobalLogic Ukraine
 
Functional Programming & Event Sourcing - a pair made in heaven
Pawel Szulc
 
Scala best practices
Alexander Zaidel
 
Functional programming in Scala
Damian Jureczko
 
Improving Correctness with Types
Iain Hull
 
Monads and Monoids by Oleksiy Dyagilev
JavaDayUA
 
Improving Correctness With Type - Goto Con Berlin
Iain Hull
 
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
What Have The Properties Ever Done For Us
Miklós Martin
 
Scala Quick Introduction
Damian Jureczko
 
Railroading into Scala
Nehal Shah
 
Generic Functional Programming with Type Classes
Tapio Rautonen
 
Monads asking the right question
Pawel Szulc
 
Functional programming in scala
Siarhiej Siemianchuk
 
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Scala for Java Developers (Silicon Valley Code Camp 13)
Ramnivas Laddad
 
Gentle Introduction to Scala
Fangda Wang
 
Functional programming with_scala
Raymond Tay
 
Improving Correctness with Types Kats Conf
Iain Hull
 
Ad

More from BoldRadius Solutions (14)

PDF
String Interpolation in Scala | BoldRadius
BoldRadius Solutions
 
PPTX
Value Classes in Scala | BoldRadius
BoldRadius Solutions
 
PDF
Scala Days Highlights | BoldRadius
BoldRadius Solutions
 
PDF
What Are For Expressions in Scala?
BoldRadius Solutions
 
PPTX
Domain Driven Design Through Onion Architecture
BoldRadius Solutions
 
PDF
Pattern Matching in Scala
BoldRadius Solutions
 
PDF
What are Sealed Classes in Scala?
BoldRadius Solutions
 
PDF
Scala: Collections API
BoldRadius Solutions
 
PDF
How To Use Higher Order Functions in Scala
BoldRadius Solutions
 
PDF
Immutability in Scala
BoldRadius Solutions
 
PDF
Scala Days 2014: Pitching Typesafe
BoldRadius Solutions
 
PDF
Code Brevity in Scala
BoldRadius Solutions
 
PDF
Demonstrating Case Classes in Scala
BoldRadius Solutions
 
PDF
Functional Programming - Worth the Effort
BoldRadius Solutions
 
String Interpolation in Scala | BoldRadius
BoldRadius Solutions
 
Value Classes in Scala | BoldRadius
BoldRadius Solutions
 
Scala Days Highlights | BoldRadius
BoldRadius Solutions
 
What Are For Expressions in Scala?
BoldRadius Solutions
 
Domain Driven Design Through Onion Architecture
BoldRadius Solutions
 
Pattern Matching in Scala
BoldRadius Solutions
 
What are Sealed Classes in Scala?
BoldRadius Solutions
 
Scala: Collections API
BoldRadius Solutions
 
How To Use Higher Order Functions in Scala
BoldRadius Solutions
 
Immutability in Scala
BoldRadius Solutions
 
Scala Days 2014: Pitching Typesafe
BoldRadius Solutions
 
Code Brevity in Scala
BoldRadius Solutions
 
Demonstrating Case Classes in Scala
BoldRadius Solutions
 
Functional Programming - Worth the Effort
BoldRadius Solutions
 

Recently uploaded (20)

PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PDF
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
PDF
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
PDF
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
PPTX
Employee salary prediction using Machine learning Project template.ppt
bhanuk27082004
 
PDF
System Center 2025 vs. 2022; What’s new, what’s next_PDF.pdf
Q-Advise
 
PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PDF
AWS_Agentic_AI_in_Indian_BFSI_A_Strategic_Blueprint_for_Customer.pdf
siddharthnetsavvies
 
PDF
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PDF
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PDF
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
Presentation about variables and constant.pptx
kr2589474
 
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
Employee salary prediction using Machine learning Project template.ppt
bhanuk27082004
 
System Center 2025 vs. 2022; What’s new, what’s next_PDF.pdf
Q-Advise
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
AWS_Agentic_AI_in_Indian_BFSI_A_Strategic_Blueprint_for_Customer.pdf
siddharthnetsavvies
 
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
Activate_Methodology_Summary presentatio
annapureddyn
 
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 

Towards Reliable Lookups - Scala By The Bay