Aug. 7th, 2012

akuklev: (Default)
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?

(https://groups.google.com/d/topic/scala-debate/DWbSe_Erkrc/discussion)

December 2016

S M T W T F S
    123
456789 10
11121314151617
18192021222324
25262728293031

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated Aug. 18th, 2025 06:08 pm
Powered by Dreamwidth Studios