Scala如何编写高效的分区函数?

时间:2014-02-22 19:44:56

标签: scala

我正在尝试编写一个非常有效的分区函数(持续一两行)。

def insert(insertOnes: Array[String]): Array[Label] = {

    val existingOnes = this.getAll // this will get "existing" things

    //this is the hard part:
    val twoArrays = insertOnes.partition(_ != insertOnes...)

    //ignore below
    var insertSeq = scala.collection.mutable.Seq[Label]()
    for(label <- diffLabels) {
      insertSeq :+= new Label(None, label)
    }
    current.dao.Labels.insertAll(insertSeq: _*)
  }

这个insert函数接受一个字符串数组,并将此数组与现有元素数组进行比较,然后将插入元素分成两个数组:一个填充未插入的元素,一个是已有的元素。我意识到通过在数组上调用diff方法来获得“不同”部分非常容易,但是如何获得数组的“相同”部分呢?

为了完成,我包含了Label案例类。

  class Labels (tag: Tag) extends Table[Label](tag, "Labels") {
    def id = column[Option[Int]]("TAG_ID", O.PrimaryKey, O.AutoInc)
    def tag_name = column[String]("TAG_NAME")

    def * = (id, tag_name) <> (Label.tupled, Label.unapply _)
  }

1 个答案:

答案 0 :(得分:2)

目前还不清楚你的起点是什么,但解决方案看起来像这样:

val existingSet = existing.toSet
val (alreadyThere, notYetThere) = insertOnes.partition(existingSet)

注意,一个集合可以作为过滤器,分区等的指示器功能;设置中的内容映射到true,而不是映射到false的内容。

如果existing的类型不正确,请使用map提取与输入匹配的字符串。

val existingSet = existing.map(_.name).toSet

我无法从你的代码中知道这是怎么做到的;它似乎可能是Label的第二个参数(你没有显示)。

相关问题