How to specialize a type parameterized argument to multiple different types for in Scala?
Posted
by jmount
on Stack Overflow
See other posts from Stack Overflow
or by jmount
Published on 2010-06-15T18:19:01Z
Indexed on
2010/06/15
18:22 UTC
Read the original article
Hit count: 262
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. What I mean is you can write:
def g(f:Array[Double]=>Double,Array[Double]):Double
but you can not write something like:
def g(f[Y]:Array[Y]=>Double,Array[Double]):Double
because Y is not known. The intended use is that inside g() I will specialize fY to multiple different types at different times. You can write:
def g[Y](f:Array[Y]=>Double,Array[Double]):Double
but then f() is of a single type per call to g() (which is exactly what we do not want).
However, you can get all of the equivalent functionality by using a trait extension instead insisting on passing around a function.
What I advocated in my article was:
1) Creating a trait that imitates the structure of Scala's Function1 trait. Something like:
abstract trait VectorFN {
def apply[Y](x:Array[Y]):Y
}
2) declaring def g(f:VectorFN,Double):Double (using the trait is the type).
This works (people here on StackOverflow helped me find it, and I am happy with it)- but am I mis-representing Scala by missing an even better solution?
© Stack Overflow or respective owner