二维数组作为函数

时间:2014-11-10 16:15:53

标签: 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)

我是否可以声明一个接受二维数组Array(Array(1))而不在函数声明中实际使用Array类型的函数?或者它是否隐式转换为Int => Array[Int]而且它是什么?

3 个答案:

答案 0 :(得分:2)

对于任意嵌套数组,您可以使用" deep"体操类型的隐式转换

  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>

这有效:

  def foo(f: Int => Int => Int => Int) = println(f(0)(0)(0))
  foo(Array(Array(Array(1))).asFunction)

答案 1 :(得分:0)

您可以使用此隐式转化

  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))

答案 2 :(得分:-1)

嗯,为什么不这样呢?

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)
  }

}

或者我完全错过了问题的重点?