来自元组的收益率

时间:2015-01-30 08:49:00

标签: scala yield

元组和产量:非常常见的结构。但令我惊讶的是,将它们组合在一起并不是很明显如何才能完成工作:

 val edges = ((1,2),(2,3),(3,4),(4,5),(1,6),(3,8),(4,9),(5,10),
 (1,7),(4,10))

  val edgesw = for (e <- edges) yield (e._1, e._2, 1.0)
   // e is interpreted as "any"
   // therefore e._1 and e._2 are invalid / do not compile

更新

添加类型参数似乎有所帮助..但为什么需要呢?

  val edgesw = for (e: (Int, Int) <- edges) yield (e._1, e._2, 1.0)

另一次更新我忽略了Seq / Array表示法!

 val edges = Seq((1,2),(2,3),(3,4),(4,5),(1,6),(3,8),(4,9),(5,10),
 (1,7),(4,10))

现在行为符合预期:

  val edgesw = for (e <- edges) yield (e._1, e._2, 1.0)
 edgesw: Seq[(Int, Int, Double)] = List((1,2,1.0), (2,3,1.0), (3,4,1.0), (4,5,1.0), (1,6,1.0), (3,8,1.0), (4,9,1.0), (5,10,1.0), (1,7,1.0), (4,10,1.0))

2 个答案:

答案 0 :(得分:1)

以下内容:

val edges = ((1,2),(2,3),(3,4),(4,5),(1,6),(3,8),(4,9),(5,10), (1,7),(4,10))
val edgesw = for (e <- edges) yield (e._1, e._2, 1.0)

无法编译。你提到的那样需要Seq所以:

scala> val edges = Seq((1,2),(2,3),(3,4),(4,5),(1,6),(3,8),(4,9),(5,10)) 
edges: Seq[(Int, Int)] = List((1,2), (2,3), (3,4), (4,5), (1,6), (3,8), (4,9), (5,10))

scala> for (e <- edges) yield (e._1, e._2, 1.0)
res2: Seq[(Int, Int, Double)] = List((1,2,1.0), (2,3,1.0), (3,4,1.0), (4,5,1.0), (1,6,1.0), (3,8,1.0), (4,9,1.0), (5,10,1.0))

因此类型推断按预期工作。

答案 1 :(得分:0)

你应该使用这样的东西:

  val edgesw = for (
    eany <- edges.productIterator;
    e = eany.asInstanceOf[(Int, Int)]
  ) yield (e._1, e._2, 1.0)

每个元组都延伸Product特征,因此具有:

def productIterator: Iterator[Any]

但是因为每个元组成员都可以包含不同类型的对象Product只能返回Iterator[Any]。由于此eany类型为Any,因此您应将其转换为(Int, Int)

<强>更新 你的UPDATE版本对我不起作用:

val edgesw = for (e: (Int, Int) <- edges) yield (e._1, e._2, 1.0)

我收到以下错误:

  

值过滤器不是((Int,Int),...)...

的成员
相关问题