gpt4 book ai didi

scala - 二维数组作为函数

转载 作者:行者123 更新时间:2023-12-01 05:08:16 24 4
gpt4 key购买 nike

可以使用一维数组作为函数

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]就这样?

最佳答案

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

  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)

关于scala - 二维数组作为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26848093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com