【问题标题】:scala: combining 2 sets of lists [duplicate]scala:组合2组列表[重复]
【发布时间】:2013-06-05 20:19:02
【问题描述】:

我正在尝试编写一个在 Scala 中组合 2 组列表的函数。第二组中的每个列表都必须附加到第一组中的每个列表以获取所有可能的排列,但是这不起作用,因为 case foo 会导致出现错误,有人知道如何解决这个问题吗?

  type foo = List[bar]
    def combine(s1:Set[foo],s2:Set[foo]):Set[foo] ={
      s1.map{
        case foo => {s2.foreach{
        case foo=> a.append(b)}}
      }.toSet
    }

我的问题主要在于如何引用地图函数中的列表。

【问题讨论】:

  • ab 是什么?
  • a 和 b 是我试图以某种方式将案例连接到 s1 和 s2 中的元素,但我不太明白如何连接它们,所以它们被保留为 a 和 b(问题的一部分)
  • 集合是可迭代的,请参阅stackoverflow.com/questions/5955797/…

标签: list scala set


【解决方案1】:

for 理解不做你想要的吗?

for{
  a <- s1
  b <- s2
} yield a.append(b)

【讨论】:

    【解决方案2】:

    如果你想用s2 附加s1 的所有元素。最简单的方法是:

    type bar = Int
    type foo = List[bar]
    def combine(s1:Set[foo], s2:Set[foo]):Set[foo] = for{
    x <- s1
    y<- s2
    } yield x ::: y
    
    val s1 = Set(List(1),List(2))
    val s2 = Set(List(3),List(4))
    combine(s1,s2)                                 
    //> res0: scala.collection.Set[collection.OwnCollection.foo] = Set(List(1, 3), 
                                                  //| List(1, 4), List(2, 3), List(2, 4))
    

    【讨论】:

      【解决方案3】:

      实现此目的的一种方法是使用 flatMap

      class Bar
      type Foo = List[Bar]
      def combine(s1: Set[Foo], s2: Set[Foo]): Set[Foo] = {
        s1.flatMap(a => s2.map(b => a ::: b))
      }
      

      请注意mapflatMap 的语法格式为collection.map(x =&gt; transform(x)),因此此处不需要case 关键字。

      一种等效的方式,稍微简洁一点,是用于理解

      def combine(s1:Set[Foo], s2:Set[Foo]): Set[Foo] = 
        for(a <- s1; b <- s2)
          yield a ::: b
      

      有关 Scala 中序列理解的介绍,您可以在这里查看:http://www.scala-lang.org/node/111

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-22
        • 1970-01-01
        • 1970-01-01
        • 2021-06-10
        • 2018-03-03
        相关资源
        最近更新 更多