SlideShare una empresa de Scribd logo
1 de 21
by Mario Fusco
Red Hat – Senior Software Engineer
mario.fusco@gmail.com
twitter: @mariofusco
Scala
the language
of languages
What is a
Domain Specific Language?
A
computer programming language
of
limited expressiveness
focused on a
particular domain
computer programming language
limited expressiveness
particular domain
2 principles driving toward
DSL development
Why use a
Domain Specific Language?
The only purpose of
languages,
even programming ones
IS COMMUNICATION
Communication is king
Written once, read many times
Always code as
if the person
who will
maintain your
code is a maniac
serial killer that
knows where
you live
"Any fool can write code
that a computer can
understand.
Good programmers
write code that humans
can understand“
Martin Fowler
Pros & Cons of DSLs
+ Expressivity  Communicativity
+ Conciseness
+ Readability  Maintainability  Modificability
+ Higher level of abstraction
+ Higher productivity in the specific problem domain
̶ Language design is hard
̶ Upfront cost
̶ Additional indirection layer  Performance concerns
̶ Lack of adeguate tool support
̶ Yet-another-language-to-learn syndrome
DSL taxonomy
 External DSL  a language having custom
syntactical rules separate from the main language of
the application it works with
 Internal DSL  a particular way of employing a
general-purpose language, using only a small subset
of the language's features
 Language workbench  a specialized IDE for
defining and building DSL, usually in a visual
way, used both to determine the structure of the
DSL and to provide an editing environment for
people using it
Internal DSL
External DSL
DSL Types Comparison
+ learning curve
+ cost of building
+ programmers familiarity
+ IDE support (autocompletion …)
+ composability
+ flexibility
+ readability
+ clear separation between
business (DSL) and host language
+ helpful when business code is
written by a separate team
(domain experts)
̶ syntactic noise
̶ needs to be recompiled
(if host language is static)
̶ need to learn of grammars
and language parsing
̶ boundary between DSL
and host language
̶ easier to grow out of
control
Internal DSL
in Scala
Scala features for internal DSL
Implicit conversion
implicit def intToRational(x: Int) = new Rational(x)
val c = 2 + a // = 8/3
Higher-Order Functions
def twice(f: => Unit): Unit = { f; f; }
twice {
println("Hello World")
}
A more complete example
Hammurabi
A Scala rule engine
The golfers problem
• A foursome of golfers is standing at a tee, in a line from left to
right. Each golfer wears different colored pants; one is
wearing red pants.
• The golfer to Fred’s immediate right is wearing blue pants.
• Joe is second in line.
• Bob is wearing plaid pants.
• Tom isn’t in position one or four, and he isn’t wearing the
hideous orange pants.
• In what order will the four golfers tee off, and what color are
each golfer’s pants?”
The Hammurabi Solution (1)
var allPos = (1 to 4).toSet
var allColors =
Set("blue", "plaid", "red", "orange")
val assign = new {
def position(p: Int) = new {
def to(person: Person) = {
person.pos = p
allPos = availablePos - p
}
}
def color(c: String) = new {
def to(person: Person) = {
person.color = c
allColors = availableColors - c
}
}
}
class Person(n: String) {
val name = n
var pos: Int = _
var color: String = _
}
The Hammurabi Solution (2)
import hammurabi.Rule._
val ruleSet = Set(
rule ("Unique positions") let {
val p = any(kindOf[Person])
when {
(availablePos.size equals 1) and (p.pos equals 0)
} then {
assign position availablePos.head to p
}
},
[……]
rule ("Person to Fred’s immediate right is wearing blue pants") let {
val p1 = any(kindOf[Person])
val p2 = any(kindOf[Person])
when {
(p1.name equals "Fred") and (p2.pos equals p1.pos + 1)
} then {
assign color "blue" to p2
}
}
)
How Hammurabi DSL works (1)
case class Rule(description: String,
bind: () => RuleDefinition[_], salience: Int = 0)
case class RuleDefinition[A](condition: () => Boolean,
execution: () => A)
def rule(description: String) = new {
def let(letClause: => RuleDefinition[_]): Rule =
Rule(description, letClause _)
def withSalience(salience: Int) = new {
def let(letClause: => RuleDefinition[_]): Rule =
Rule(description, letClause _, salience)
}
}
rule ("An extremly useful rule") withSalience 5 let {
...
}
How Hammurabi DSL works (2)
def when(condition: => Boolean) = new {
def then[A](execution: => A): RuleDefinition =
RuleDefinition(condition _, execution _)
}
rule("Joe is in position 2") let {
val p = any(kindOf[Person])
when {
p.name equals "Joe"
} then {
assign position 2 to p
}
}
def ruleExecution() = {
val ruleDef = rule.bind()
if (ruleDef.condition()) ruleDef.execution()
}
External DSL
in Scala
A Scala Parser
abstract class Parser[+T] extends (Input => ParserResult[T])
trait Parsers {
sealed abstract class ParseResult[+T] { val next: Input }
case class Success[+T](result: T, override val next: Input)
extends ParseResult[T] { ... }
sealed abstract class NoSuccess(val msg: String,
override val next: Input)
extends ParseResult[Nothing] { ... }
case class Failure(override val msg: String,
override val next: Input)
extends NoSuccess(msg, next) { ... }
case class Error(override val msg: String,
override val next: Input)
extends NoSuccess(msg, next) { ... }
}
Parser Combinators
Combinator Symbol Description
Sequence ~ If two parsers P and Q are combined using the sequential
combinator, the parsing succeeds if:
■ P successfully consumes a part of the input stream
■ Q following P consumes the input that P did not consume
Alternation | A parser combinator for composing alternatives.
Selective
sequence
~>
<~
Selectively keep only either the right or the left result of a
sequence combinator
Repetition rep… A combinator that works on a parser P and returns another
parser that parses one or more repetitions of what P parses
Function
application
^^
^^^
A combinator that allows a function to be applied on a
parser, resulting in a new parser.
Variation Explanation
(rep(p), p*) Repeat p 0+ times
(rep1(p), p+) Repeat p 1+ times
(repN(n, p)) Repeat p exactly n times

Más contenido relacionado

Destacado (20)

Infographic on Scala Programming Language
Infographic on Scala Programming LanguageInfographic on Scala Programming Language
Infographic on Scala Programming Language
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Maven c'est bien, SBT c'est mieux
Maven c'est bien, SBT c'est mieuxMaven c'est bien, SBT c'est mieux
Maven c'est bien, SBT c'est mieux
 
Universitélang scala tools
Universitélang scala toolsUniversitélang scala tools
Universitélang scala tools
 
Les monades Scala, Java 8
Les monades Scala, Java 8Les monades Scala, Java 8
Les monades Scala, Java 8
 
Université des langages scala
Université des langages   scalaUniversité des langages   scala
Université des langages scala
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Lagom, reactive framework
Lagom, reactive frameworkLagom, reactive framework
Lagom, reactive framework
 
Scala #2
Scala #2Scala #2
Scala #2
 
Scala lecture #4
Scala lecture #4Scala lecture #4
Scala lecture #4
 
Павел Павлов - Scala для профессионалов - Joker 2013
Павел Павлов - Scala для профессионалов - Joker 2013Павел Павлов - Scala для профессионалов - Joker 2013
Павел Павлов - Scala для профессионалов - Joker 2013
 
Feature suggester
Feature suggesterFeature suggester
Feature suggester
 
Scala #4
Scala #4Scala #4
Scala #4
 
Scala plugin for IntelliJ IDEA
Scala plugin for IntelliJ IDEAScala plugin for IntelliJ IDEA
Scala plugin for IntelliJ IDEA
 
Erlang
ErlangErlang
Erlang
 
Scala #5
Scala #5Scala #5
Scala #5
 
Lec 2
Lec 2Lec 2
Lec 2
 
Backend: Пишем на Scala для браузера
Backend: Пишем на Scala для браузераBackend: Пишем на Scala для браузера
Backend: Пишем на Scala для браузера
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)
 

Similar a Scala: the language of languages - Mario Fusco (Red Hat)

Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataKernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataAnne Nicolas
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable LispAstrails
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a MomentSergio Gil
 
Specialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingSpecialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingPositive Hack Days
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 

Similar a Scala: the language of languages - Mario Fusco (Red Hat) (20)

Hammurabi
HammurabiHammurabi
Hammurabi
 
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataKernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
 
Specialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingSpecialized Compiler for Hash Cracking
Specialized Compiler for Hash Cracking
 
Elixir introduction
Elixir introductionElixir introduction
Elixir introduction
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
50 shades of PHP
50 shades of PHP50 shades of PHP
50 shades of PHP
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt17
ppt17ppt17
ppt17
 
ppt30
ppt30ppt30
ppt30
 

Más de Scala Italy

Alessandro Abbruzzetti - Kernal64
Alessandro Abbruzzetti - Kernal64Alessandro Abbruzzetti - Kernal64
Alessandro Abbruzzetti - Kernal64Scala Italy
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsScala Italy
 
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaAndrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaScala Italy
 
Stefano Rocco, Roberto Bentivoglio - Scala in increasingly demanding environm...
Stefano Rocco, Roberto Bentivoglio - Scala in increasingly demanding environm...Stefano Rocco, Roberto Bentivoglio - Scala in increasingly demanding environm...
Stefano Rocco, Roberto Bentivoglio - Scala in increasingly demanding environm...Scala Italy
 
Federico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesFederico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesScala Italy
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaScala Italy
 
Daniela Sfregola - Intro to Akka
Daniela Sfregola - Intro to AkkaDaniela Sfregola - Intro to Akka
Daniela Sfregola - Intro to AkkaScala Italy
 
Mirco Dotta - Akka Streams
Mirco Dotta - Akka StreamsMirco Dotta - Akka Streams
Mirco Dotta - Akka StreamsScala Italy
 
Phil Calçado - Your microservice as a function
Phil Calçado - Your microservice as a functionPhil Calçado - Your microservice as a function
Phil Calçado - Your microservice as a functionScala Italy
 
Scalatra - Massimiliano Dessì (Energeya)
Scalatra - Massimiliano Dessì (Energeya)Scalatra - Massimiliano Dessì (Energeya)
Scalatra - Massimiliano Dessì (Energeya)Scala Italy
 
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...Scala Italy
 
Simplifying development-short - Mirco Dotta (Typesafe)
Simplifying development-short - Mirco Dotta (Typesafe)Simplifying development-short - Mirco Dotta (Typesafe)
Simplifying development-short - Mirco Dotta (Typesafe)Scala Italy
 
Scala in pratica - Stefano Rocco (MoneyFarm)
Scala in pratica - Stefano Rocco (MoneyFarm)Scala in pratica - Stefano Rocco (MoneyFarm)
Scala in pratica - Stefano Rocco (MoneyFarm)Scala Italy
 

Más de Scala Italy (13)

Alessandro Abbruzzetti - Kernal64
Alessandro Abbruzzetti - Kernal64Alessandro Abbruzzetti - Kernal64
Alessandro Abbruzzetti - Kernal64
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.js
 
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaAndrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
 
Stefano Rocco, Roberto Bentivoglio - Scala in increasingly demanding environm...
Stefano Rocco, Roberto Bentivoglio - Scala in increasingly demanding environm...Stefano Rocco, Roberto Bentivoglio - Scala in increasingly demanding environm...
Stefano Rocco, Roberto Bentivoglio - Scala in increasingly demanding environm...
 
Federico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesFederico Feroldi - Scala microservices
Federico Feroldi - Scala microservices
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
 
Daniela Sfregola - Intro to Akka
Daniela Sfregola - Intro to AkkaDaniela Sfregola - Intro to Akka
Daniela Sfregola - Intro to Akka
 
Mirco Dotta - Akka Streams
Mirco Dotta - Akka StreamsMirco Dotta - Akka Streams
Mirco Dotta - Akka Streams
 
Phil Calçado - Your microservice as a function
Phil Calçado - Your microservice as a functionPhil Calçado - Your microservice as a function
Phil Calçado - Your microservice as a function
 
Scalatra - Massimiliano Dessì (Energeya)
Scalatra - Massimiliano Dessì (Energeya)Scalatra - Massimiliano Dessì (Energeya)
Scalatra - Massimiliano Dessì (Energeya)
 
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...
 
Simplifying development-short - Mirco Dotta (Typesafe)
Simplifying development-short - Mirco Dotta (Typesafe)Simplifying development-short - Mirco Dotta (Typesafe)
Simplifying development-short - Mirco Dotta (Typesafe)
 
Scala in pratica - Stefano Rocco (MoneyFarm)
Scala in pratica - Stefano Rocco (MoneyFarm)Scala in pratica - Stefano Rocco (MoneyFarm)
Scala in pratica - Stefano Rocco (MoneyFarm)
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 

Último (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 

Scala: the language of languages - Mario Fusco (Red Hat)

  • 1. by Mario Fusco Red Hat – Senior Software Engineer mario.fusco@gmail.com twitter: @mariofusco Scala the language of languages
  • 2. What is a Domain Specific Language? A computer programming language of limited expressiveness focused on a particular domain computer programming language limited expressiveness particular domain
  • 3. 2 principles driving toward DSL development Why use a Domain Specific Language?
  • 4. The only purpose of languages, even programming ones IS COMMUNICATION Communication is king
  • 5.
  • 6. Written once, read many times Always code as if the person who will maintain your code is a maniac serial killer that knows where you live
  • 7. "Any fool can write code that a computer can understand. Good programmers write code that humans can understand“ Martin Fowler
  • 8. Pros & Cons of DSLs + Expressivity  Communicativity + Conciseness + Readability  Maintainability  Modificability + Higher level of abstraction + Higher productivity in the specific problem domain ̶ Language design is hard ̶ Upfront cost ̶ Additional indirection layer  Performance concerns ̶ Lack of adeguate tool support ̶ Yet-another-language-to-learn syndrome
  • 9. DSL taxonomy  External DSL  a language having custom syntactical rules separate from the main language of the application it works with  Internal DSL  a particular way of employing a general-purpose language, using only a small subset of the language's features  Language workbench  a specialized IDE for defining and building DSL, usually in a visual way, used both to determine the structure of the DSL and to provide an editing environment for people using it
  • 10. Internal DSL External DSL DSL Types Comparison + learning curve + cost of building + programmers familiarity + IDE support (autocompletion …) + composability + flexibility + readability + clear separation between business (DSL) and host language + helpful when business code is written by a separate team (domain experts) ̶ syntactic noise ̶ needs to be recompiled (if host language is static) ̶ need to learn of grammars and language parsing ̶ boundary between DSL and host language ̶ easier to grow out of control
  • 12. Scala features for internal DSL Implicit conversion implicit def intToRational(x: Int) = new Rational(x) val c = 2 + a // = 8/3 Higher-Order Functions def twice(f: => Unit): Unit = { f; f; } twice { println("Hello World") }
  • 13. A more complete example Hammurabi A Scala rule engine
  • 14. The golfers problem • A foursome of golfers is standing at a tee, in a line from left to right. Each golfer wears different colored pants; one is wearing red pants. • The golfer to Fred’s immediate right is wearing blue pants. • Joe is second in line. • Bob is wearing plaid pants. • Tom isn’t in position one or four, and he isn’t wearing the hideous orange pants. • In what order will the four golfers tee off, and what color are each golfer’s pants?”
  • 15. The Hammurabi Solution (1) var allPos = (1 to 4).toSet var allColors = Set("blue", "plaid", "red", "orange") val assign = new { def position(p: Int) = new { def to(person: Person) = { person.pos = p allPos = availablePos - p } } def color(c: String) = new { def to(person: Person) = { person.color = c allColors = availableColors - c } } } class Person(n: String) { val name = n var pos: Int = _ var color: String = _ }
  • 16. The Hammurabi Solution (2) import hammurabi.Rule._ val ruleSet = Set( rule ("Unique positions") let { val p = any(kindOf[Person]) when { (availablePos.size equals 1) and (p.pos equals 0) } then { assign position availablePos.head to p } }, [……] rule ("Person to Fred’s immediate right is wearing blue pants") let { val p1 = any(kindOf[Person]) val p2 = any(kindOf[Person]) when { (p1.name equals "Fred") and (p2.pos equals p1.pos + 1) } then { assign color "blue" to p2 } } )
  • 17. How Hammurabi DSL works (1) case class Rule(description: String, bind: () => RuleDefinition[_], salience: Int = 0) case class RuleDefinition[A](condition: () => Boolean, execution: () => A) def rule(description: String) = new { def let(letClause: => RuleDefinition[_]): Rule = Rule(description, letClause _) def withSalience(salience: Int) = new { def let(letClause: => RuleDefinition[_]): Rule = Rule(description, letClause _, salience) } } rule ("An extremly useful rule") withSalience 5 let { ... }
  • 18. How Hammurabi DSL works (2) def when(condition: => Boolean) = new { def then[A](execution: => A): RuleDefinition = RuleDefinition(condition _, execution _) } rule("Joe is in position 2") let { val p = any(kindOf[Person]) when { p.name equals "Joe" } then { assign position 2 to p } } def ruleExecution() = { val ruleDef = rule.bind() if (ruleDef.condition()) ruleDef.execution() }
  • 20. A Scala Parser abstract class Parser[+T] extends (Input => ParserResult[T]) trait Parsers { sealed abstract class ParseResult[+T] { val next: Input } case class Success[+T](result: T, override val next: Input) extends ParseResult[T] { ... } sealed abstract class NoSuccess(val msg: String, override val next: Input) extends ParseResult[Nothing] { ... } case class Failure(override val msg: String, override val next: Input) extends NoSuccess(msg, next) { ... } case class Error(override val msg: String, override val next: Input) extends NoSuccess(msg, next) { ... } }
  • 21. Parser Combinators Combinator Symbol Description Sequence ~ If two parsers P and Q are combined using the sequential combinator, the parsing succeeds if: ■ P successfully consumes a part of the input stream ■ Q following P consumes the input that P did not consume Alternation | A parser combinator for composing alternatives. Selective sequence ~> <~ Selectively keep only either the right or the left result of a sequence combinator Repetition rep… A combinator that works on a parser P and returns another parser that parses one or more repetitions of what P parses Function application ^^ ^^^ A combinator that allows a function to be applied on a parser, resulting in a new parser. Variation Explanation (rep(p), p*) Repeat p 0+ times (rep1(p), p+) Repeat p 1+ times (repN(n, p)) Repeat p exactly n times