【问题标题】:Scala - compare two Option[Seq[String]]Scala - 比较两个 Option[Seq[String]]
【发布时间】:2016-09-18 16:53:46
【问题描述】:

我是 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)
  }
}

【问题讨论】:

  • 嗯,我的 StackOverflow 代码格式似乎也有问题。 ..
  • 当您执行someSeqAB1.toList 时,您将获得List[Seq[String]]。尝试对此列表进行排序时遇到错误,因为 Seq[String] 没有定义隐式排序。
  • someSeqAB1.toList 编译是因为OptionIterable,由这种隐式转换引起:scala.Option#option2IterableOption.toListOption.isDefined 时为您提供单例 List,否则为空列表。欢迎来到 Scala。
  • 在完成了不同的转换之后,我现在有以下可以编译和工作的assert(someSeqAB1.getOrElse(Seq("")).toList.sorted == someSeqBA.getOrElse(Seq("")).toList.sorted)

标签: scala collections


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    由于您使用的是Matchers,我建议您这样做:

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

    【讨论】:

    • 是的,正如你所看到的,我也是 scalatest 的新手 :)
    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2020-08-12
    • 2014-12-03
    • 1970-01-01
    相关资源
    最近更新 更多