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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- [Angular] Communicate with Angular Elements using Input
- 为什么&>> system()调用在3.3和3.4之间有不同的行为
- angularjs – 递归ui路由器嵌套视图
- 如何在bash脚本中组合AND和OR条件用于if条件?
- Ubuntu+Nginx+PHP WEB环境配置的因php-fpm配置引起的502错误
- 在runit/daemontools监督下运行docker进程是否合理
- scala – SortedSet map并不总是保留结果中的元素排序?
- bash – sudo cat << EOF>文件不起作用,sudo su
- bash – 如何从终端运行.sh或.bat文件?
- 透视和调整你的企业和商务系统(Ⅳ:WebService、dotNET)