8

私がやりたいのは、リスト内の要素をソートするのではなく、Scala で List オブジェクトをソートすることです。たとえば、Int のリストが 2 つあるとします。

val l1 = List(1, 2, 3, 7)
val l2 = List(1, 2, 3, 4, 10)

l1>l2の順番で並べたいです。

必要なことを行うケースクラスを作成しましたが、問題は、それを使用すると他のメソッドが機能しないことです。クラス内の他のすべてのメソッド、つまり flatten、sortWith などを実装する必要がありますか?

私のクラスコードは次のようになります。

class ItemSet(itemSet: List[Int]) extends Ordered[ItemSet] {

  val iSet: List[Int] = itemSet

  def compare(that: ItemSet) = {

    val thisSize = this.iSet.size
    val thatSize = that.iSet.size
    val hint = List(thisSize, thatSize).min
    var result = 0
    var loop = 0

    val ths = this.iSet.toArray
    val tht = that.iSet.toArray

    while (loop < hint && result == 0) {
      result = ths(loop).compare(tht(loop))
      loop += 1
    }
    if (loop == hint && result == 0 && thisSize != thatSize) {
      thisSize.compare(thatSize)
    } else
      result
  }

}

ItemSet の配列を作成すると、並べ替えることができます。

val is1 = new ItemSet(List(1, 2, 5, 8))
val is2 = new ItemSet(List(1, 2, 5, 6))
val is3 = new ItemSet(List(1, 2, 3, 7, 10))

Array(is1, is2, is3).sorted.foreach(i => println(i.iSet))

scala> List(1, 2, 3, 7, 10)
List(1, 2, 5, 6)
List(1, 2, 5, 8)

私に問題を与えている2つの方法は次のとおりです。

def itemFrequencies(transDB: Array[ItemSet]): Map[Int, Int] = transDB.flatten.groupBy(x => x).mapValues(_.size)

私が得るエラーは次のとおりです。

タイプ Map[Nothing, Int] の式は、期待されるタイプ Map[Int, Int] に準拠していません

そして、これについて:

def sortListAscFreq(transDB: Array[ItemSet], itemFreq: Map[Int, Int]): Array[List[Int]] = {
  for (l <- transDB) yield
    l.sortWith(itemFreq(_) < itemFreq(_))
}

私は得る:

シンボル sortWith を解決できません。

List[Int] を拡張して、他のメソッドの機能を失わずにリストのコレクションをソートできる方法はありますか?

4

1 に答える 1

15

標準ライブラリは、順序付けられたもののコレクションに対して辞書式順序付けを提供します。それをスコープに入れることができ、完了です:

scala> import scala.math.Ordering.Implicits._
import scala.math.Ordering.Implicits._

scala> val is1 = List(1, 2, 5, 8)
is1: List[Int] = List(1, 2, 5, 8)

scala> val is2 = List(1, 2, 5, 6)
is2: List[Int] = List(1, 2, 5, 6)

scala> val is3 = List(1, 2, 3, 7, 10)
is3: List[Int] = List(1, 2, 3, 7, 10)

scala> Array(is1, is2, is3).sorted foreach println
List(1, 2, 3, 7, 10)
List(1, 2, 5, 6)
List(1, 2, 5, 8)

Ordering型クラスは多くの場合、Scalaよりも便利ですOrdered。コードを変更したり、 を拡張するプロキシ クラスを作成したりすることなく、既存の型の順序を指定することができますOrdered[Whatever]

于 2013-07-05T16:11:29.143 に答える