[英]Map tuples to tuples using Iterator
Why is the following code does not work, and how can I overcome it using Iterator
? 为什么以下代码不起作用,如何使用
Iterator
克服它?
def f(str : String) : (String, String) = {
str.splitAt(1)
}
var with_id : Iterator[(String, Int)] = List(("test", 1), ("list", 2), ("nothing", 3), ("else", 4)).iterator
println(with_id.mkString(" "))
val result = with_id map { (s : String, i : Int) => (f(s), i) }
println(result.mkString(" "))
Expected output is: 预期输出为:
(("t", "est"), 1) (("l", "ist"), 2) ...
Error: 错误:
Error:(28, 54) type mismatch;
found : (String, Int) => ((String, String), Int)
required: ((String, Int)) => ?
val result = with_id map { (s : String, i : Int) => (f(s), i) }
^
The problem is that (s : String, i : Int) => (f(s), i)
is a Function2
(ie a function that takes 2 arguments): 问题是
(s : String, i : Int) => (f(s), i)
是一个Function2
(即一个带有2个参数的函数):
scala> (s : String, i : Int) => (f(s), i)
res3: (String, Int) => ((String, String), Int) = <function2>
whereas .map
expects a Function1
(taking a tuple as its argument). 而
.map
需要一个Function1
(以元组作为参数)。
You could define a Function1
with 您可以使用定义一个
Function1
scala> val g = (t: (String, Int)) => (f(t._1), t._2)
g: ((String, Int)) => ((String, String), Int) = <function1>
scala> val result = with_id map g
result: Iterator[((String, String), Int)] = non-empty iterator
But it seems much better (to me at least) to use the more idiomatic pattern matching anonymous function (note the added case
) : 但是(至少对我而言)使用更惯用的模式匹配匿名函数(注意添加的
case
)似乎要好得多(请注意):
scala> val result = with_id map { case (s : String, i : Int) => (f(s), i) }
result: Iterator[((String, String), Int)] = non-empty iterator
with_id.map
expects a ((String, Int) => ?)
function as input. with_id.map
需要一个((String, Int) => ?)
函数作为输入。 That is, a function that takes a Tuple
as input, not two parameters. 也就是说,该函数将
Tuple
作为输入,而不是两个参数。
You can use it like this: 您可以像这样使用它:
with_id map{ case (s,i) => (f(s), i)} //match the input tuple to s and i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.