Eleco
Eleco

Reputation: 3244

Idiomatic use of QuickSort in Scala

def sort(s:String)={
   val a= s.toCharArray ()
   scala.util.Sorting.quickSort(array)
   new String(a)
}
  1. is there a more succint way to write the above - while keeping the call to QuickSort ?
  2. why is the quicksort mutating the array in place instead of returning a new array (isnt that what functional languages are supposed to do ?)

Upvotes: 0

Views: 150

Answers (1)

Rüdiger Klaehn
Rüdiger Klaehn

Reputation: 12565

  1. I don't see anything wrong with the sort method. If you want an in-place quicksort this is probably the best you are going to get.

  2. Scala is not a pure functional language. It tries making a functional style pleasant to use, but if you want to use imperative style for performance or other reasons there is nothing wrong with it. In fact in addition to allowing functional style, scala is also a much better OO language than java.

See the talk from Martin Odersky, the creator of the language, about when to use mutable state. ScalaDays 2013 Keynote

In any case, as long as mutable state is confined to the local variables of a method, it is pretty harmless and easy to reason about. The sort method is pure / referentially transparent from the outside even though it uses mutable state inside.

By the way: if you want an immutable transform version of sort that works on strings, it also exists. It probably does something similar to your sort method internally.

scala> "BCAD".sorted
res5: String = ABCD

Upvotes: 4

Related Questions