SlideShare a Scribd company logo
Expression Problem
Giuseppe Scopelliti
Platform Engineer | @peppescopellit1
Agenda
➢ Introduction
➢ Set up a use case
➢ Proposed solution
➢ Talk about pros and cons
➢ Q/A
Introduction 1/2
The expression problem is one in which the challenge
is:
➢ Define a data type with cases.
➢ Add new cases of the type, and operations for the
types.
➢ Avoid recompiling.
Introduction 2/2
Any implementation of the expression problem should
satisfy the following requirements:
➢ Extensibility in both dimensions.
➢ Strong static type safety.
➢ No modification of the existing code.
➢ Separate compilation.
Use case 1/3
We are using a third party library
case class Employee(name: String, id : Long)
trait Payroll {
def processEmployees(employees: Vector[Employee]): Either[String, Throwable]
}
Use case 2/3
We can easily add new types
class USPayroll extends Payroll {
def processEmployees(employees: Vector[Employee]) = Left("US payroll")
}
class JapanPayroll extends Payroll {
def processEmployees(employees: Vector[Employee]) = Left("Japan payroll")
}
Use case 3/3
What if we need to add new operations on the types?
E.g. Deal with Contractors
trait ExtendedPayroll extends Payroll {
def processEmployees(employees: Vector[Employee]): Either[String, Throwable]
def processContractors(contractors: Vector[Contractor]): Either[String, Throwable]
}
In summary
OP
TYPE
This is a practical problem
How to add features to an
existing system
incrementally without
doing modifications?
Proposed solution
➔ Leverage scala traits and abstract type members to
solve the expression problem.
➔ Rewrite the same payroll system, so you can easily
add new operations to it, without breaking type-
safety, and at the same time add a new type.
Some Code 1/5The new payroll system will be:
trait PayrollSystem {
case class Employee(name: String, id: Long)
type P <: Payroll
trait Payroll {
def processEmployees(employees: Vector[Employee]): Either[String, Throwable]
}
def processPayroll(p: P): Either[String, Throwable]
}
// You nest everything inside a trait so that you can treat it as a module.
// The type P denotes some subtype of the Payroll trait,
// which declares an abstract method to process salaries for employees.
// The processPayroll method needs to be implemented to process payrolls for a
// given Payroll type.
Some Code 2/5We can still easily add a new type
trait USPayrollSystem extends PayrollSystem {
class USPayroll extends Payroll {
def processEmployees(employees: Vector[Employee]) = {
println("US payroll")
Left("US payroll")
}
}
}
PayrollSystem
USPayrollSystem
Some Code 3/5What about a new operation ?
trait ContractorPayrollSystem extends PayrollSystem {
case class Contractor(name: String)
//Shadowing the Payroll trait defined in PayrollSystem
trait Payroll extends super.Payroll {
def processContractors(contractors: Vector[Contractor]): Either[String,
Throwable]
}
}
PayrollSystem
USPayrollSystem
ContractorPayrollSystem
Some Code 4/5And ...
trait USContractorPayrollSystem extends USPayrollSystem with ContractorPayrollSystem
{
//We are shadowing the former definition of USPayroll.
class USPayroll extends super.USPayroll with Payroll {
def processContractors(contractors: Vector[Contractor]) = {
println("US contract payroll")
Left("US contract payroll")
}
}
}
PayrollSystem
USPayrollSystem
ContractorPayrollSystem
USContractorPayrollSystem
Some Code 5/5Finally ...
object USEmployeeAndContractorPayroll extends USContractorPayrollSystem {
type P = USPayroll
def processPayroll(p: USPayroll): Either[String, Throwable] = {
p.processEmployees(Vector(Employee("a", 1)))
p.processContractors(Vector(Contractor("b")))
Left("payroll processed successfully")
}
}
Proposed solution
This was a good example to demonstrate:
– The power of Scala’s type system
– The abstraction available to build scalable and
extensible components
We achieved a solution
OP
TYPE
Pros And Cons
– Inside the context, shadowing let you extend the old
definition, without overriding it.
– Shadowing can introduce unintended errors in your
code.
Thanks for listening!
Any Questions?
Some resources to get more details
❖ http://www.scala-lang.org/docu/files/TheExpressionProblem.pdf
❖ https://news.ycombinator.com/item?id=11683379
❖ http://fileadmin.cs.lth.se/sde/people/gorel/misc/ExpProblemTalkPart1.
pdf
❖ http://lambda-the-ultimate.org/node/3141
❖ https://prezi.com/wwqo9dtgqhs2/comparing-solutions-to-the-
expression-problem-in-scala-and-r/

More Related Content

PPSX
Type conversion
PPTX
Type casting in c programming
DOCX
Type conversion in c
PDF
write a List class to store your Vehicle objects. you've decided that your im...
PPTX
Data Type Conversion in C++
PPTX
Python functions part10
PDF
Composite types
PPTX
Vectors
Type conversion
Type casting in c programming
Type conversion in c
write a List class to store your Vehicle objects. you've decided that your im...
Data Type Conversion in C++
Python functions part10
Composite types
Vectors

What's hot (20)

PPTX
14 initialization & cleanup
PDF
Write a List class to store Vehicle objects. The implementation of List will ...
PDF
Write a List class to store Vehicle objects. The implementation of List will ...
PPTX
Method parameters in c#
PDF
PPT
Effective Java - Always override toString() method
PPT
Struct
PDF
Structures and Pointers
PPTX
Function
PDF
Introduction to C++
PPTX
2CPP18 - Modifiers
PDF
Handout # 4 functions + scopes
PPTX
Function overloading
PPTX
Computer techniques for optimization of cycle of operations
PPTX
Type Conversion, Precedence and Associativity
DOC
5.program structure
PPTX
Functions in c
PPT
Rrelational algebra in dbms overview
PDF
CSEG1001 Unit 5 Structure and Unions
PPTX
Unit 7: Built-In Functions
14 initialization & cleanup
Write a List class to store Vehicle objects. The implementation of List will ...
Write a List class to store Vehicle objects. The implementation of List will ...
Method parameters in c#
Effective Java - Always override toString() method
Struct
Structures and Pointers
Function
Introduction to C++
2CPP18 - Modifiers
Handout # 4 functions + scopes
Function overloading
Computer techniques for optimization of cycle of operations
Type Conversion, Precedence and Associativity
5.program structure
Functions in c
Rrelational algebra in dbms overview
CSEG1001 Unit 5 Structure and Unions
Unit 7: Built-In Functions
Ad

Similar to Expression Problem in Scala (20)

PPTX
Scala Back to Basics: Type Classes
PPTX
Improving Correctness with Types
PDF
Type classes 101 - classification beyond inheritance
PPTX
Improving Correctness with Types Kats Conf
PDF
Demystifying Type Class derivation with Shapeless
PDF
Inheritance And Traits
PDF
Scala for Java Developers
PPTX
Improving Correctness With Type - Goto Con Berlin
PPTX
Monads and friends demystified
PDF
Going bananas with recursion schemes for fixed point data types
PDF
Scala or functional programming from a python developer's perspective
PDF
Generic Functional Programming with Type Classes
PDF
Data Centric Metaprocessing by Vlad Ulreche
PDF
Data centric Metaprogramming by Vlad Ulreche
PDF
Oh, All the things you'll traverse
PDF
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
PDF
From OOP To FP Through A Practical Case
PDF
Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...
PDF
Few simple-type-tricks in scala
PDF
Introducing Monads and State Monad at PSUG
Scala Back to Basics: Type Classes
Improving Correctness with Types
Type classes 101 - classification beyond inheritance
Improving Correctness with Types Kats Conf
Demystifying Type Class derivation with Shapeless
Inheritance And Traits
Scala for Java Developers
Improving Correctness With Type - Goto Con Berlin
Monads and friends demystified
Going bananas with recursion schemes for fixed point data types
Scala or functional programming from a python developer's perspective
Generic Functional Programming with Type Classes
Data Centric Metaprocessing by Vlad Ulreche
Data centric Metaprogramming by Vlad Ulreche
Oh, All the things you'll traverse
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
From OOP To FP Through A Practical Case
Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...
Few simple-type-tricks in scala
Introducing Monads and State Monad at PSUG
Ad

Recently uploaded (20)

PDF
PPT on Performance Review to get promotions
PPT
Project quality management in manufacturing
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
Geodesy 1.pptx...............................................
PPTX
OOP with Java - Java Introduction (Basics)
PDF
Well-logging-methods_new................
PPTX
web development for engineering and engineering
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
737-MAX_SRG.pdf student reference guides
DOCX
573137875-Attendance-Management-System-original
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
additive manufacturing of ss316l using mig welding
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPT on Performance Review to get promotions
Project quality management in manufacturing
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Geodesy 1.pptx...............................................
OOP with Java - Java Introduction (Basics)
Well-logging-methods_new................
web development for engineering and engineering
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
737-MAX_SRG.pdf student reference guides
573137875-Attendance-Management-System-original
CYBER-CRIMES AND SECURITY A guide to understanding
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
additive manufacturing of ss316l using mig welding
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf

Expression Problem in Scala

  • 2. Agenda ➢ Introduction ➢ Set up a use case ➢ Proposed solution ➢ Talk about pros and cons ➢ Q/A
  • 3. Introduction 1/2 The expression problem is one in which the challenge is: ➢ Define a data type with cases. ➢ Add new cases of the type, and operations for the types. ➢ Avoid recompiling.
  • 4. Introduction 2/2 Any implementation of the expression problem should satisfy the following requirements: ➢ Extensibility in both dimensions. ➢ Strong static type safety. ➢ No modification of the existing code. ➢ Separate compilation.
  • 5. Use case 1/3 We are using a third party library case class Employee(name: String, id : Long) trait Payroll { def processEmployees(employees: Vector[Employee]): Either[String, Throwable] }
  • 6. Use case 2/3 We can easily add new types class USPayroll extends Payroll { def processEmployees(employees: Vector[Employee]) = Left("US payroll") } class JapanPayroll extends Payroll { def processEmployees(employees: Vector[Employee]) = Left("Japan payroll") }
  • 7. Use case 3/3 What if we need to add new operations on the types? E.g. Deal with Contractors trait ExtendedPayroll extends Payroll { def processEmployees(employees: Vector[Employee]): Either[String, Throwable] def processContractors(contractors: Vector[Contractor]): Either[String, Throwable] }
  • 9. This is a practical problem How to add features to an existing system incrementally without doing modifications?
  • 10. Proposed solution ➔ Leverage scala traits and abstract type members to solve the expression problem. ➔ Rewrite the same payroll system, so you can easily add new operations to it, without breaking type- safety, and at the same time add a new type.
  • 11. Some Code 1/5The new payroll system will be: trait PayrollSystem { case class Employee(name: String, id: Long) type P <: Payroll trait Payroll { def processEmployees(employees: Vector[Employee]): Either[String, Throwable] } def processPayroll(p: P): Either[String, Throwable] } // You nest everything inside a trait so that you can treat it as a module. // The type P denotes some subtype of the Payroll trait, // which declares an abstract method to process salaries for employees. // The processPayroll method needs to be implemented to process payrolls for a // given Payroll type.
  • 12. Some Code 2/5We can still easily add a new type trait USPayrollSystem extends PayrollSystem { class USPayroll extends Payroll { def processEmployees(employees: Vector[Employee]) = { println("US payroll") Left("US payroll") } } } PayrollSystem USPayrollSystem
  • 13. Some Code 3/5What about a new operation ? trait ContractorPayrollSystem extends PayrollSystem { case class Contractor(name: String) //Shadowing the Payroll trait defined in PayrollSystem trait Payroll extends super.Payroll { def processContractors(contractors: Vector[Contractor]): Either[String, Throwable] } } PayrollSystem USPayrollSystem ContractorPayrollSystem
  • 14. Some Code 4/5And ... trait USContractorPayrollSystem extends USPayrollSystem with ContractorPayrollSystem { //We are shadowing the former definition of USPayroll. class USPayroll extends super.USPayroll with Payroll { def processContractors(contractors: Vector[Contractor]) = { println("US contract payroll") Left("US contract payroll") } } } PayrollSystem USPayrollSystem ContractorPayrollSystem USContractorPayrollSystem
  • 15. Some Code 5/5Finally ... object USEmployeeAndContractorPayroll extends USContractorPayrollSystem { type P = USPayroll def processPayroll(p: USPayroll): Either[String, Throwable] = { p.processEmployees(Vector(Employee("a", 1))) p.processContractors(Vector(Contractor("b"))) Left("payroll processed successfully") } }
  • 16. Proposed solution This was a good example to demonstrate: – The power of Scala’s type system – The abstraction available to build scalable and extensible components
  • 17. We achieved a solution OP TYPE
  • 18. Pros And Cons – Inside the context, shadowing let you extend the old definition, without overriding it. – Shadowing can introduce unintended errors in your code.
  • 20. Some resources to get more details ❖ http://www.scala-lang.org/docu/files/TheExpressionProblem.pdf ❖ https://news.ycombinator.com/item?id=11683379 ❖ http://fileadmin.cs.lth.se/sde/people/gorel/misc/ExpProblemTalkPart1. pdf ❖ http://lambda-the-ultimate.org/node/3141 ❖ https://prezi.com/wwqo9dtgqhs2/comparing-solutions-to-the- expression-problem-in-scala-and-r/