函数参数的模式匹配 [英] Pattern matching on function parameters
问题描述
我有一个元组向量
val l = for {i <- 1 to 5} yield (i,i*2)
Vector((1,2), (2,4), (3,6), (4,8), (5,10))
我想用以下方式总结:
l.reduce((x,y) => (x._1+y._1, x._2+y._2))
(15,30)
但使用模式匹配.
如果函数只有一个参数,我知道怎么做,即:l.map({case(a,b)=>a+b})
,但我不能t 让它使用两个参数工作.这就是我试图做的:
I know how to do it if the function gets only one parameter, ie: l.map({case(a,b)=>a+b})
, but I can't get it to work with two parameters. this is what I tried to do:
l.reduce({(case(a,b),case(c,d))=>(a+c,b+d)})
但这行不通.
所以我的问题是,如何解包作为函数参数出现的 2 个元组?
So my question is, how can I unpack 2 tuples that come as a function parameters?
推荐答案
只需明确指定类型即可帮助偏函数机制:
Just specify type explicitly to help partial functions mechanism:
l.reduce[(Int, Int)]{ case ((a,b), (c, d)) => (a + b, c + d)}
没有 [(Int, Int)]
Scala 无法为您的部分函数推断正确的类型
Without [(Int, Int)]
scala can't infer correct type for your partial function
附言如果您想知道为什么会看到关于 String
的错误,而不管您实际使用的是什么类型(在您的情况下是 Int
):
P.S. If you're intersesting why you see this error about String
regardless what type you're actually using (it's Int
in your case):
found : Any ,
required: String
那是因为Predef
中的字符串隐含+".这不是这种隐式的唯一问题 - 您可以查看 SI-194.
That's because of implicit "+" for strings in Predef
. It's not the only problem with this implicit - you may look at SI-194.
即使没有:
l.reduce{ case ((a,b), (c, d)) => (a, d)}
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: (?, ?) => ?
scala 无法推断类型,因为它无法推断部分函数的类型 - 可能是 Int 的任何超类型:(A1, A1) =>A1
预期,其中 [A1 >: A]
scala was unable to infer the type, because it can't infer a type for partial function - may be any supertype of Int: (A1, A1) => A1
expected, where [A1 >: A]
这篇关于函数参数的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!