Created
April 7, 2019 11:36
-
-
Save lutzh/986bb220237ec43e976f24c139c104b8 to your computer and use it in GitHub Desktop.
Currency example for Mathias
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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