加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 二维数组作为函数

发布时间:2020-12-16 08:44:05 所属栏目:安全 来源:网络整理
导读:可以使用一维数组作为函数 def foo1(f: Int = Int) = ???foo1(Array(1)) 可以使用带有两个参数列表的函数 def foo2(f: Int = Int = Int) = ???def plus(x: Int)(y: Int) = x + yfoo2(plus) 我可以声明一个接受二维数组Array(Array(1))而不在函数声明中实际使
可以使用一维数组作为函数

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 =>数组[Int]就是这样吗?

解决方法

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

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读