在 map、flatmap、...偏函数中使用元组 [英] Using Tuples in map, flatmap,... partial functions
本文介绍了在 map、flatmap、...偏函数中使用元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我这样做:
val l = Seq(("un", ""), ("deux", "hehe"), ("trois", "lol"))
l map { t => t._1 + t._2 }
没关系.
如果我这样做:
val l = Seq(("un", ""), ("deux", "hehe"), ("trois", "lol"))
l map { case (b, n) => b + n }
没关系.
但如果我这样做:
val l = Seq(("un", ""), ("deux", "hehe"), ("trois", "lol"))
l map { (b, n) => b + n }
它不会起作用.
为什么要使用case"关键字来使用命名元组?
It will not work.
Why should I use "case" keyword to use named tuples?
推荐答案
2.11的错误信息解释性更强:
The error message with 2.11 is more explanatory:
scala> l map { (b, n) => b + n }
<console>:9: error: missing parameter type
Note: The expected type requires a one-argument function accepting a 2-Tuple.
Consider a pattern matching anonymous function, `{ case (b, n) => ... }`
l map { (b, n) => b + n }
^
<console>:9: error: missing parameter type
l map { (b, n) => b + n }
^
对于申请,您将获得自动元组":
For an apply, you get "auto-tupling":
scala> def f(p: (Int, Int)) = p._1 + p._2
f: (p: (Int, Int))Int
scala> f(1,2)
res0: Int = 3
你提供了两个参数而不是一个.
where you supplied two args instead of one.
但您不会自动取消配对.
But you don't get auto-untupling.
人们一直希望它以这种方式工作.
这篇关于在 map、flatmap、...偏函数中使用元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文