【问题标题】:scala: generating tuples from a listscala:从列表中生成元组
【发布时间】:2015-08-14 13:49:37
【问题描述】:

我有一个列表val l=List(4,3,2,1),我正在尝试生成格式为(4,3), (4,2) 的元组列表等等。

这是我目前所拥有的:

for (i1<-0 to l.length-1;i2<-i1+1 to l.length-1) yield (l(i1),l(i2))

输出为:Vector((4,3), (4,2), (4,1), (3,2), (3,1), (2,1))

两个问题:

  1. 它生成Vector,而不是List。这两者有何不同?

  2. 这是idiomatic scala 的做法吗?我对 Scala 很陌生,所以正确学习对我来说很重要。

【问题讨论】:

    标签: list scala functional-programming


    【解决方案1】:

    在问题的第一部分,for comprehension 实现将范围 0 to l.length-1i1+1 to l.length-1 定义为 IndexedSeq[Int],因此产生的类型是 trait IndexedSeq[(Int, Int)] 由 final 类实现 Vector

    在第二部分,您的方法是有效的,但请考虑以下我们不使用对列表的索引引用的情况,

    for (List(a,b,_*) <- xs.combinations(2).toList) yield (a,b)
    

    注意

    xs.combinations(2).toList
    List(List(4, 3), List(4, 2), List(4, 1), List(3, 2), List(3, 1), List(2, 1))
    

    所以对于List(a,b,_*),我们进行模式匹配并提取每个嵌套列表的前两个元素(_* 表示忽略可能的附加元素)。由于迭代是在一个列表上进行的,因此 for 推导会产生一个重复列表。

    【讨论】:

    • 谢谢,你有什么理由使用 List(a,b,_*) 而不仅仅是 List(a,b)?
    猜你喜欢
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2017-04-14
    • 1970-01-01
    相关资源
    最近更新 更多