如何返回List元素的Cartesian

时间:2015-02-27 16:26:58

标签: scala

我有3个元素的列表1,2,3:

  val s : List[String] = List("1" , "2" , "3")    //> s  : List[String] = List(1, 2, 3)

When I attempt to extract a cartesian of these elements : 
  s.map(m => m.map(m2 => (m,m2)))                 //> res0: List[scala.collection.immutable.IndexedSeq[(String, Char)]] = List(Vec
                                                  //| tor((1,1)), Vector((2,2)), Vector((3,3)))

为什么不返回列表元素的笛卡尔积?

1 个答案:

答案 0 :(得分:3)

 s.map(m => m.map(m2 => (m,m2)))  
       ^ This is a String, which is being treated as a Seq[Char]

 s.map(m => m.map(m2 => (m,m2)))  
                  ^ This is a Char in the String, of which there is only one in each.

如果String更长,则更容易看到失败的原因。

scala> val s : List[String] = List("1a" , "2b" , "3c")
s: List[String] = List(1a, 2b, 3c)

scala> s.map(m => m.map(m2 => (m,m2))) 
res1: List[scala.collection.immutable.IndexedSeq[(String, Char)]] = List(Vector((1a,1), (1a,a)), Vector((2b,2), (2b,b)), Vector((3c,3), (3c,c)))

内部map需要使用相同的种子列表:

scala> for(a <- s; b <- s) yield (a, b)
res7: List[(Int, Int)] = List((1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3))

或者:

scala> s.flatMap(a => s.map(b => (a, b)))
res8: List[(Int, Int)] = List((1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3))