繁体   English   中英

使用Iterator将元组映射到元组

[英]Map tuples to tuples 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(" "))

预期输出为:

(("t", "est"), 1) (("l", "ist"), 2) ...

错误:

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) }
                                                 ^

问题是(s : String, i : Int) => (f(s), i)是一个Function2 (即一个带有2个参数的函数):

scala> (s : String, i : Int) => (f(s), i)
res3: (String, Int) => ((String, String), Int) = <function2>

.map需要一个Function1 (以元组作为参数)。

您可以使用定义一个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

但是(至少对我而言)使用更惯用的模式匹配匿名函数(注意添加的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需要一个((String, Int) => ?)函数作为输入。 也就是说,该函数将Tuple作为输入,而不是两个参数。

您可以像这样使用它:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM