二维数组作为函数 [英] Two dimensional array as a function

查看:56
本文介绍了二维数组作为函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在

def foo1(f: Int => Int) = ???
foo1(Array(1))

可以使用带有两个参数列表的函数

It's possible to use a function with two argument lists in

def foo2(f: Int => Int => Int) = ???
def plus(x: Int)(y: Int) = x + y
foo2(plus)

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

Can I declare a function that will accept a two-dimensional array Array(Array(1)) without actually using Array type in function declaration? Or is it implicitly converted to Int => Array[Int] and that's it?

推荐答案

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

For arbitrary nested arrays you can use "deep" implicit conversion with type gymnastics

  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 控制台示例

Example in scala console

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)

这篇关于二维数组作为函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆