Embedded Domain Specific Languages (eDSL) in Scala
An informal uninformed introduction
Today's menu
Domain Specific Languages
Uses
External DSLs
Scala support (parser combinators)
Internal/embedded DSLs
Sample(s)
Scala support
Let's try yo build one?
Domain Specific Languages
What are they?
"A Domain-Specific Language is a programming language that mimics the terms, idioms, and expressions used among experts in the targeted domain" Programming Scala - A. Payne, D. Wampler
Why?
Two types
Domain Specific Languages
Advantages
Disadvantages
External DSL
val ID = """[a-zA-Z]([a-zA-Z0-9]|_[a-zA-Z0-9])*"""r� val NUM = """[1-9][0-9]*"""r� def program = clazz*� def classPrefix = "class" ~ ID ~ "(" ~ formals ~ ")"� def classExt = "extends" ~ ID ~ "(" ~ actuals ~ ")"� def clazz = classPrefix ~ opt(classExt) ~ "{" ~ (member*) ~ "}"� def formals = repsep(ID ~ ":" ~ ID, ",")� def actuals = expr*� def member = (� "val" ~ ID ~ ":" ~ ID ~ "=" ~ expr� | "var" ~ ID ~ ":" ~ ID ~ "=" ~ expr� | "def" ~ ID ~ "(" ~ formals ~ ")" ~ ":" ~ ID ~ "=" ~ expr� | "def" ~ ID ~ ":" ~ ID ~ "=" ~ expr� | "type" ~ ID ~ "=" ~ ID� )
embedded DSLs
Some (Scala) DSL examples
Tools (embedded DSL)
EDF Trading (external DSL)
Some (Scala) eDSL examples
def expr(a:Boolean,b:Boolean,c:Boolean,d:Boolean)=� ( (a Λ b) V ¬(a Λ c) ) Λ ( (c V d) Λ ¬(b) )
...
val payrollCalculator = rules { employee =>
employee salary_for 2.weeks minus_deductions_for { gross =>
federalIncomeTax is (25. percent_of gross)�stateIncomeTax is (5. percent_of gross)�insurancePremiums are (500. in gross.currency)�retirementFundContributions are (10. percent_of gross)
}
}
...� // use premium pricing strategy for order� new Order to buy(100 sharesOf "IBM")� maxUnitPrice 300� using premiumPricing,
embedded DSLs: Support in Scala
Scala building blocks for embedded DSLs:
(and more)
(... thinking about it... most of Scala )
Interesting links
http://debasishg.blogspot.com/2008/05/designing-internal-dsls-in-scala.html
(he's working on a book all bout DSLs)
http://programming-scala.labs.oreilly.com/ch11.html
Show me the code!!
Let's keep in touch!
Twitter: @gclaramunt
Blog: http://gabrielsw.blogspot.com