scala:从列表中生成元组

riv*_*ivu 3 functional-programming scala list

我有一个列表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很新,所以对我来说,我学得很对.

elm*_*elm 6

上的问题的第一部分,用于理解实现定义范围0 to l.length-1i1+1 to l.length-1作为IndexedSeq[Int]因而产生型性状是IndexedSeq[(Int, Int)]由最终类实现Vector.

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

for (List(a,b,_*) <- xs.combinations(2).toList) yield (a,b)
Run Code Online (Sandbox Code Playgroud)

注意

xs.combinations(2).toList
List(List(4, 3), List(4, 2), List(4, 1), List(3, 2), List(3, 1), List(2, 1))
Run Code Online (Sandbox Code Playgroud)

因此List(a,b,_*)我们使用模式匹配并提取每个嵌套列表的前两个元素(_*指示忽略可能的其他元素).由于迭代是在列表上,因此for comprehension产生一个双列表.