簡體   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