views:

55

answers:

3

Ok, I wouldn't be coming to You for help if I knew what to do, anyways, still having problems with my "program".

class Mark(val name: String, val style_mark: Double, val other_mark: Double) {}

object Test extends Application
  {
  val m1 = new Mark("Smith", 18, 16);
  val m2 = new Mark("Cole", 14, 7);
  val m3 = new Mark("James", 13, 15);
  val m4 = new Mark("Jones", 14, 16);
  val m5 = new Mark("Richardson", 20, 19);
  val m6 = new Mark("James", 4, 18);

  val marks = List[Mark](m1, m2, m3, m4, m5, m6);

  def avg(xs: List[Double]) = xs.sum / xs.length

  val marksGrouped = marks.groupBy(_.name).map { kv => new Mark(kv._1, avg(kv._2.map(_.style_mark)), avg(kv._2.map(_.other_mark))) }

  val marksSorted = marksGrouped.sortWith((m1, m2) => m1._style_mark < m2._style_mark)

  }

And this is the error I get: error: value sortWith is not a member of scala.collection.immutable.Iterable[Mark]

+3  A: 

You'll have to call toList on marksGrouped first. Iterable does not have a sortWith method, but List does.

sepp2k
He needs to call `toSeq`...
Daniel
+3  A: 

For extra higher-order programming goodness, use sortBy, rather than sortWith

  val marksSorted = marksGrouped.toList.sortBy(_.style_mark)
Dave Griffith
+2  A: 

Basic collection hierarchy:

  • TraversableOnce: might only be traversable once, like iterators.
  • Traversable: May be traversed, with foreach, but no other guarantees provided.
  • Iterable: Can produce iterator, which enables lazy traversal.
    • Seq: contents have a fixed traversal order.
      • IndexedSeq: contents can be efficiently retrieved by position number.
    • Set: contents only contain one element of each type.
    • Map: contents can be efficiently retrieved by a key.

So the problem you face is that Iterable does not provide support to define the traversal order, which is what sortWith does. Only collections derived from Seq can -- List, Vector, ArrayBuffer, etc.

The method toSeq will return a Seq out of an Iterable. Or you may choose a more specific collection, with characteristics well matched to your algorithm.

Daniel