views:

243

answers:

1

I need a back-check (please).

In an article ( http://www.win-vector.com/blog/2010/06/automatic-differentiation-with-scala/ ) I just wrote I stated that it is my belief in Scala that you can not specify a function that takes an argument that is itself a function with an unbound type parameter. I have edited this question to try and simplify the example.

The following code works by introducing a trait GenericFn that imitates the Scala Function1 trait, except it has a free-type parameter in the function:

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))
    }
}

This works, but is there a way to do this without the GenericFn trait (use a standard function notation)? For example the code below fails with the compile-time error: "type mismatch; found : TypeExample2.A required: _$1 where type _$1 <: TypeExample2.NumberBase":

def specializeAndApplyTwice(f:(_<:NumberBase)=>String):String = {
   f(new A()) + f(new B())
}
+2  A: 
buraq
I heavily edited the question to try and slot your example in. I couldn't get it to work- but obviously that may be my fault (I don't know much about the various _ notations).
jmount
In the reformulated question, it seems simpler to use<code>def specializeAndApplyTwice(f:NumberBase=>String)</code>...I believe there is added difficulty in the original formulation because one needed to use the type parameter (or the wildcard type _) to build an Array type. BTW for completeness: functions from types to values are well known in theory (the calculus is called F-omega) but Scala does not have them in their pure form. Would need an suitable VM._ in types always means a wildcard type. Maybe you find this page useful, it has some examples http://www.scala-lang.org/node/43
buraq