如何在地图中嵌入if语句

时间:2016-02-03 17:18:55

标签: scala if-statement apache-spark

我有一个来自矩阵的每个组合的定义计算余弦相似度。但是,我希望定义在某些条件下运行。

定义如下:

def neighbours(signatures: Iterable[Signature], minCosineSimilarity: Double): Iterator[MatrixEntry] = {
   signatures.
      toSeq.
      sortBy(_.index). // sort in order to create an upper triangular matrix
      combinations(2)
      .map {
        case first :: other :: nil =>
        if((first.index < 4 && other.index > 3) || (first.index > 3 && other.index < 4)){}
        val cosine = Cosine(first.vector, other.vector)
        MatrixEntry(first.index, other.index, cosine)
    }.
      filter(_.value >= minCosineSimilarity)
  }

它计算来自&#34;组合(2)&#34;的给定对的余弦相似度。线。我添加了一行包含if语句。如果条件在这里有效,我该怎么做?

2 个答案:

答案 0 :(得分:4)

使用collect代替map。然后,您可以使用if guard

  .collect {
    case first :: other :: nil if (first.index < 4 && other.index > 3) || (first.index > 3 && other.index < 4) =>
    val cosine = Cosine(first.vector, other.vector)
    MatrixEntry(first.index, other.index, cosine)
  }

答案 1 :(得分:0)

我相信你想要的是MatrixEntity,只有在你写的if语句为真时才能计算出来。如果是这样,那么这应该有用......

def neighbours(signatures: Iterable[Signature], minCosineSimilarity: Double): Iterator[MatrixEntry] = {
  signatures.
  toSeq.
  sortBy(_.index). // sort in order to create an upper triangular matrix
  combinations(2)
  .map {
    case first :: other :: nil =>
    if((first.index < 4 && other.index > 3) || (first.index > 3 && other.index < 4)){
        val cosine = Cosine(first.vector, other.vector)
        Some(MatrixEntry(first.index, other.index, cosine))
    }else{None} 
  }.filter{ 
    _.exists{_.value >= minCosineSimilarity}
    }.map{_.get}
}