function – 如何在Scala中将类型参数化参数专门化为多个不同类
我需要反击(请).
在一篇文章(http://www.win-vector.com/blog/2010/06/automatic-differentiation-with-scala/)中我写道,我说我对Scala的信念是你不能指定一个带有参数的函数,该参数本身就是一个带有未绑定类型参数的函数.我已编辑此问题以尝试简化示例. 下面的代码通过引入模仿Scala Function1特征的特征GenericFn来工作,除了它在函数中有一个free-type参数: object TypeExample { trait NumberBase { def result:String } class A extends NumberBase { def result = "A" } class B extends NumberBase { def result = "B" } trait GenericFn { def apply[X<:NumberBase](x:X):String } def specializeAndApplyTwice(f:GenericFn):String = { f[A](new A()) + f[B](new B()) } def main(args : Array[String]) : Unit = { val f = new GenericFn { def apply[X<:NumberBase](x:X):String = { x.result } } println(specializeAndApplyTwice(f)) } } 这有效,但有没有一种方法可以在没有GenericFn特征的情况下执行此操作(使用标准函数表示法)?例如,下面的代码失败并出现编译时错误:“type mismatch; found:TypeExample2.A required:_ $1 where type _ $1<:TypeExample2.NumberBase”: def specializeAndApplyTwice(f:(_<:NumberBase)=>String):String = { f(new A()) + f(new B()) } 解决方法
重申问题的最初动机:我们想给一个值’g’的类型,因为我们想传递它. Scala值(当然)不能具有多态类型,即使它们是函数值.那么如何给出其中某些部分未知的类型?
所以我相信一种解决方案是使用通配符(一种存在抽象形式): def g(f: Array[_ <: NumberBase[_]] => Double,z: Array[Double]): Double 关于g类型的散文解释是:从Array [T]和Array [Double]到Double的函数,其中T是扩展Double的某种类型. “some”是表示存在抽象的词,我们要求这种类型存在,尽管我们在这一点上并不关心它是哪一种. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |