Skip to content

Instantly share code, notes, and snippets.

@lutzh
Created April 7, 2019 11:36
Show Gist options
  • Save lutzh/986bb220237ec43e976f24c139c104b8 to your computer and use it in GitHub Desktop.
Save lutzh/986bb220237ec43e976f24c139c104b8 to your computer and use it in GitHub Desktop.
Currency example for Mathias
// Start Scala
// :paste the following:
object Currencies {
sealed trait Rate {
def to(currency: Rate, amount: Double): Money
}
case object EUR extends Rate {
override def to(currency: Rate, amount: Double): Money =
currency match {
case EUR => Money(EUR, amount)
case USD => Money(USD, amount * 1.12)
}
}
case object USD extends Rate {
override def to(currency: Rate, amount: Double): Money =
currency match {
case EUR => Money(EUR, amount * 0.89)
case USD => Money(USD, amount)
}
}
case class Money(currency: Rate, amount: Double) {
def to(targetCurrency: Rate) = currency.to(targetCurrency, amount)
}
}
object Convert {
def EUR(amount: Double): Currencies.Money = Currencies.Money(Currencies.EUR, amount)
def USD(amount: Double): Currencies.Money = Currencies.Money(Currencies.USD, amount)
}
// -- press CRTL-D
// scala> import Currencies._
// import Currencies._
// scala> Convert EUR 5 to USD
// res0: Currencies.Money = Money(USD,5.6000000000000005)
// scala> Convert USD 5 to EUR
// res1: Currencies.Money = Money(EUR,4.45)
@lutzh
Copy link
Author

lutzh commented Apr 7, 2019

Of course a proper currency DSL in Scala would look completely different, this is just what I produced in a few minutes to match the syntax requested in https://twitter.com/mathiasverraes/status/1114822981400838146

For a "proper" currency DSL watch this: https://www.youtube.com/watch?v=W37Mp3mBYLw

For a general DSL for dealing with units of measurement see https://www.squants.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment