Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Scala中从元组执行函数_Scala_Function_Lambda_Functional Programming_Tuples - Fatal编程技术网

在Scala中从元组执行函数

在Scala中从元组执行函数,scala,function,lambda,functional-programming,tuples,Scala,Function,Lambda,Functional Programming,Tuples,我有一个元组,其中存储了匿名函数,我想遍历它们并执行它们 val functions = ((x:Int, y:Int) => x + y, (x:Int, y: Int) => x - y) // I want to execute the anonymous functions in the Tuple functions.productIterator.foreach(function => function) 不幸的是,我不能这样做 functions.product

我有一个元组,其中存储了匿名函数,我想遍历它们并执行它们

val functions = ((x:Int, y:Int) => x + y, (x:Int, y: Int) => x - y)
// I want to execute the anonymous functions in the Tuple
functions.productIterator.foreach(function => function)
不幸的是,我不能这样做

functions.productIterator.foreach(function => function(1, 2))


出路是什么

元组上的
产品迭代器
返回
迭代器[Any]
,而不是您所期望的
迭代器[Function2[Int,Int,Int]

元组不应该被迭代。类型丢失是因为元组中的每个条目都可以是不同的类型,因此类型系统只假设
Any
(因此
迭代器[Any]
)。因此,真正的建议是,如果要迭代,请使用
Seq
Set
之类的集合

另一方面,如果您知道元组包含特定类型的函数,则可以通过使用
asInstanceOf
强制转换来绕过类型检查,但不建议这样做,因为类型检查是您的朋友

functions.productIterator.map(_.asInstanceOf[(Int,Int)=>Int](1, 2))
// produces `Iterator(3, -1)`

或者,查看中的HLists,它具有元组和集合的属性。

我们可以将元组的元素提取到
序列中,同时保留类型信息;因此

Seq(functions._1, functions._2).map(_(1,2))
List(3, -1)

同意,在这种情况下我该如何应对;是否有方法进行模式匹配,然后执行函数。
Seq(functions._1, functions._2).map(_(1,2))
List(3, -1)