Alexander Kuklev (akuklev) wrote,
Alexander Kuklev

Implicit Defaults

Often there are many implementations of data structures and algorithms with different performance. Currently, Scala provides sensible defaults:
val xs = List(1, 5, 2, 8, 4)
val xSorted = xs.sort
Unfortunatelly, there is no elegant way to override the defaults both locally or for an entire scope. In our opinion the most elegant way to achieve it are the implicits. If factories and methods with multiple implementation would accept the desired implementation as an implicit argument, this is how we'd be able to override the defaults:
implicit val sortMethod = SortMethod.TimSort
implicit val listVariant = ListVariant.DoublyLinkedList
val xs = List(1, 5, 2, 8, 4)
val xSorted = xs.sort
// and now override them locally
val xs2 = List(1, 5, 2, 8, 4)(ListVariant.XorList)
val xSorted2 = xs.sort(SortMethod.QuickSort)
This approach could be extended to numeric literals, we need the literals 42 to be intepreted as Int("42") where Int.apply takes an implicit argument "variant" (Int16, Int32, Int64, BigInteger) and 42.1 as Fractional("42.1") with implicit argument "variant" (Float, Double, Decimal, BigDecimal, FixedPoint(accuracy), Rational(accuracy), ContFraction(accuracy)):
implicit val intVariant = IntVariant.BigInteger
val x = 234794320943279322878

In order to completely separate implementation/optimization details from the substantial part of the algorithm, we need an analogon of Cascading Style Sheets. I would propose the following format:
«scope selector» {
  «type» = «implicit value of that type»

Here's an example:
com.miriamlaurel.test432 {
  SortMethod = QuickSort
  Ordering[String] = AlphabeticOrders.Swedish
  FractVariant = BigDecimal

  TestObj#cacheCriticalMethod {
    SortMethod = ShellSort

I'd also provide the !important keyword from CSS with an optional argument "salience" for manual control of implicits priorities.
IntVariant = BigDecimal !important(100)
Apart from support for numeric literals, everything described above can be implemented with means already present in Scala 2.10 (mainly, macros). What do you think?

Tags: scala

  • (no subject)

    Встретил фотографию толпы футбольных фанатов, и она меня скорее напугала, у меня уж точно нет желания быть там среди них. Но внезапно я понял, что…

  • Прогресс

    Десять дней назад, вторая ступень SpaceX'овского корабля Starship своим ходом слетала своим ходом на десять километров вверх, и усмепшно приземлилась…

  • О водосбережении

    Как известно, питьевая вода во многих странах дефицитный ресурс. И даже в дождливой Германии летом иногда случаются засухи, в результате которых она…

  • Post a new comment


    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.