Scala - 比较两个选项[Seq [String]]

时间:2016-09-18 16:53:46

标签: scala collections

我是Scala语言的新手 - 我似乎在找到正确的语法进行排序和比较两个Option [Seq [String]]时遇到了问题。无论内容顺序如何,这两者应该是平等的。此测试的最后一行失败。我希望这段代码足以记录这个问题。

  package seqtest

import org.scalatest.{Matchers, FlatSpec}

class SortCollectionsTest extends FlatSpec with Matchers {

  "Different seq order" should "not affect equality" in {

    val seqAB1 = Seq("A","B")
    val seqAB2 = Seq("A","B")
    // two different sequences are equal
    assert(seqAB1 == seqAB2)

    val seqBA1 = Seq("B","A")
    // two different sequences are not equal if different order
    assert(seqAB1 != seqBA1)

    // but is possible to convert sequence to list and sort
    assert(seqAB1.toList.sorted == seqBA1.toList.sorted)


    // now do the same thing with Option

    val someSeqAB1 = Some(Seq("A","B"))
    val someSeqAB2 = Some(Seq("A","B"))
    // two different option sequences are equal
    assert(someSeqAB1 == someSeqAB2)

    val someSeqBA = Some(Seq("B","A"))
    // two different optional sequences are not equal if different order
    assert(someSeqAB1 != someSeqBA)

    // Option can be converted into list (unsorted)
    assert(someSeqAB1.toList != someSeqBA.toList)

    // problem
    // two different optional sequences cannot be sorted
    // compilation error
    // Error:(42, 30) No implicit Ordering defined for Seq[String].
    // Error:(42, 30) not enough arguments for method sorted: (implicit ord: scala.math.Ordering[Seq[String]])List[Seq[String]].
    // Unspecified value parameter ord.
    assert(someSeqAB1.toList.sorted == someSeqBA.toList.sorted)
  }
}

2 个答案:

答案 0 :(得分:2)

我认为更简单的解决方案是映射选项:

assert(someSeqAB1.map{ _.sorted } == someSeqBA.map{ _.sorted })

顺便说一句,对于排序版本,断言是相等的。

答案 1 :(得分:0)

由于您正在使用Matchers,我建议您执行以下操作:

someSeqAB1 should not be empty
someSeqBA should not be empty
someSeqAB1.get should contain theSameElementsAs someSeqBA.get