Scala 二维数组作为函数
可以使用一维数组作为Scala 二维数组作为函数,scala,Scala,可以使用一维数组作为 def foo1(f: Int => Int) = ??? foo1(Array(1)) 在一个函数中可以使用两个参数列表 def foo2(f: Int => Int => Int) = ??? def plus(x: Int)(y: Int) = x + y foo2(plus) 我是否可以声明一个函数,该函数将接受二维数组数组(数组(1)),而不在函数声明中实际使用array类型?或者它是隐式转换为Int=>Array[Int],就是这样吗?您可
def foo1(f: Int => Int) = ???
foo1(Array(1))
在一个函数中可以使用两个参数列表
def foo2(f: Int => Int => Int) = ???
def plus(x: Int)(y: Int) = x + y
foo2(plus)
我是否可以声明一个函数,该函数将接受二维数组
数组(数组(1))
,而不在函数声明中实际使用array
类型?或者它是隐式转换为Int=>Array[Int]
,就是这样吗?您可以使用这种隐式转换
def foo2(f: Int => Int => Int) = println(f(0)(0))
implicit def arrTof[T](arr: Array[Array[Int]]): Int => Int => Int =
arr.apply _ andThen (_.apply)
val arr2 = Array(Array(10))
foo2(arr2)
foo2(arr2.apply _ andThen (_.apply))
或者没有隐式转换
def foo2(f: Int => Int => Int) = println(f(0)(0))
implicit def arrTof[T](arr: Array[Array[Int]]): Int => Int => Int =
arr.apply _ andThen (_.apply)
val arr2 = Array(Array(10))
foo2(arr2)
foo2(arr2.apply _ andThen (_.apply))
对于任意嵌套数组,可以使用“深”隐式转换和类型转换
trait ToIdxFunction[X[_], A] {
type Result
def toIdx(x: X[A]): Int => Result
}
trait LowerPriorityDeepFunctor {
implicit def plainArray[A] =
new ToIdxFunction[Array, A] {
type Result = A
def toIdx(x: Array[A]): Int => Result = {
i => x(i)
}
}
}
object ToIdxFunction extends LowerPriorityDeepFunctor {
implicit def nestedArray[A](implicit inner: ToIdxFunction[Array, A]) = {
new ToIdxFunction[Array, Array[A]] {
type Result = Int => inner.Result
def toIdx(x: Array[Array[A]]): Int => Result = {
i => inner.toIdx(x(i))
}
}
}
}
import ToIdxFunction._
implicit class Ops[X[_], A](self: X[A]) {
def asFunction(implicit F: ToIdxFunction[X, A]) = F.toIdx(self)
}
scala控制台中的示例
scala> Array(1).asFunction
res4: Int => Int = <function1>
scala> Array(Array(1)).asFunction
res5: Int => (Int => Int) = <function1>
scala>
scala> Array(Array(Array(1))).asFunction
res6: Int => (Int => (Int => Int)) = <function1>
scala> Array(Array(Array(Array(1)))).asFunction
res7: Int => (Int => (Int => (Int => Int))) = <function1>
那么,为什么不做这样的事情呢
object Main {
def fooNforFunctions(f: Int => _): Unit = {
f(0) match {
case g: Array[_] =>
fooNforFunctions(g)
case i: Int =>
println(i)
}
}
def main(args: Array[String]): Unit = {
val arr3 = Array(Array(Array(3)))
val arr4 = Array(Array(Array(Array(4))))
fooNforFunctions(arr3)
fooNforFunctions(arr4)
}
}
还是我完全没有抓住问题的重点?谢谢。尽管我想知道是否有可能用一些奇怪的体操对任意维度的数组进行这样的转换?
foo1
案例之所以有效,是因为array
被隐式转换为WrappedArray
,它扩展了函数[Int,
。另一个原因是:转换将不适用于内部数组,并且WrappedArray
不是协变的,因此即使转换确实适用,WrappedArray[WrappedArray[Int]]
也不会扩展WrappedArray[Int=>Int]
。它“有效”,但是它不是类型安全的-您的fooNforFunctions
将接受任何f:Int=>X
,如果X
是例如String
,则在运行时失败。Scala用户通常希望代码类型良好。