如何在 Scala 中的对列表上调用 .map()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12914121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call .map() on a list of pairs in Scala
提问by akiva
I want to call map()on a list of pairs, but I get a type mismatch error.
我想调用map()对列表,但出现类型不匹配错误。
For example, suppose I want to map a List of pairs of Int to a list of their sums:
例如,假设我想将 Int 对列表映射到它们的总和列表:
scala> val ll=List((1,2),(3,4),(5,6))
ll: List[(Int, Int)] = List((1,2), (3,4), (5,6))
scala> ll.map((x:Int,y:Int)=>x+y)
<console>:9: error: type mismatch;
found : (Int, Int) => Int
required: ((Int, Int)) => ?
ll.map((x:Int,y:Int)=>x+y)
^
By the way, when trying to run foreach() I get a very similar error:
顺便说一下,当尝试运行 foreach() 时,我得到了一个非常相似的错误:
scala> ll.foreach((x:Int,y:Int)=>println(x,y))
<console>:9: error: type mismatch;
found : (Int, Int) => Unit
required: ((Int, Int)) => ?
ll.foreach((x:Int,y:Int)=>println(x,y))
^
What does the ?sign stand for? What am I missing here?
什么是?标志代表什么?我在这里错过了什么?
回答by Kim Stebel
You can use pattern matchingto get the elements of the pair.
您可以使用模式匹配来获取对的元素。
ll.map{ case (x:Int,y:Int) => x + y }
You don't even need to specify the types:
您甚至不需要指定类型:
ll.map{ case (x, y) => x + y }
The same works with foreachof course.
foreach当然,同样的作品。
The error message tells you that the compiler expected to find a function of oneparameter (a pair of ints) to any type (the question mark) and instead found a function of twoparameters, both ints.
错误消息告诉您,编译器希望找到任何类型(问号)的一个参数(一对整数)的函数,而是找到了两个参数(均为整数)的函数。
回答by Brian Agnew
You can use:
您可以使用:
ll.map(x => x._1 + x._2)
where xstands for the tuple itself, or
wherex代表元组本身,或
ll.map(x:(Int,Int) => x._1 + x._2)
if you want to declare the types explicitly.
如果要显式声明类型。
回答by Luigi Plinge
You can tuplea function, which means going from one that takes N args to one that takes 1 arg that is an N-tuple. The higher-order function to do this is available on the Functionobject. This results in nice syntax plus the extra type safety highlighted in the comments to Brian Agnew's answer.
你可以对一个函数进行元组化,这意味着从一个需要 N 个参数的函数到一个需要 1 个参数的 N 元组。执行此操作的高阶函数在Function对象上可用。这导致了很好的语法以及在对 Brian Agnew 的回答的评论中突出显示的额外类型安全。
import Function.tupled
ll map tupled(_ + _)
回答by Xavier Guihot
Note that with Dotty(foundation of Scala 3), parameter untuplinghas been extended, allowing such a syntax:
请注意,使用Dotty(foundation of Scala 3)扩展了参数解组,允许使用以下语法:
List((1, 2), (3, 4), (5, 6)).map(_ + _)
// List(3, 7, 11)
where each _refers in order to the associated tuple part.
其中 each_指的是为了关联的元组部分。

