1

How can I select the second smallest element after that a list has been sorted?

With this code I get an error and I do not understand why.

object find_the_median {
  val L = List(2,4,1,2,5,6,7,2)

  L(2)
  L.sorted(2) // FIXME returns an error
}
Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
Donbeo
  • 17,067
  • 37
  • 114
  • 188
  • Just a note that you can find the median in O(n), if it matters: http://stackoverflow.com/questions/4201292/on-algorithm-to-find-the-median-of-a-collection-of-numbers – The Archetypal Paul Dec 29 '14 at 09:57

1 Answers1

7

It's because sorted receives implicitly an Ordering argument, and when you do it like L.sorted(2) the typechecker thinks you want to pass 2 as an Ordering. So one way to do it in one line is:

L.sorted.apply(2)

or to avoid the apply pass the ordering explicitly:

L.sorted(implicitly[Ordering[Int]])(2)

which I admit is somewhat confussing so I think the best one is in two lines:

val sorted = L.sorted
sorted(2)

(You may also want to adhere to the Scala convention of naming variables with lowercase).

miguel
  • 714
  • 7
  • 17
  • I think that the last version requires more memory than the previous two – Donbeo Dec 29 '14 at 00:29
  • There's no reason it requires more memory just because you name the result of L.sorted. – The Archetypal Paul Dec 29 '14 at 09:55
  • @Paul is right. Just because a new val is defined it doesn't mean it is allocating more memory. If I'm correct, in both cases, as the sorted array won't be used anymore, it will be collected by the garbage collector. – miguel Dec 29 '14 at 15:00