The following is possible in Scala:
scala> val l = List
l: scala.collection.immutable.List.type = scala.collection.immutable.List$@7960c21a
scala> l ( 1, 2, 3 )
res0: List[Int] = List(1, 2, 3)
In other words, Scala has higher-order polymorphism. I would like to use higher-order polymorphism to do the following.
sealed abstract class A { def eval () : A }
case class A0 () extends A { ... }
case class A1 ( a : A ) extends A { ... }
case class A2 ( a : A, b : A ) extends A { ... }
....
So I have a bunch of case classes, subclasses of A, whose constructors don’t necessarily take the same numbers of arguments. I also would like to have a ‘generic’ case class, something like this:
case class ApplyA ( c : ???, l : List [ A ] ) extends A {
def eval () : A = { ??? } }
The idea is that ApplyA takes as first argument a constructor for something that is a subtype of A, and a list of arguments. The eval method then constructs an appropriate class with the constructor if possible (i.e. the list has the right length) and returns it
(this corresponds to l ( 1, 2, 3) in the List example above). What would be the type of the argument of the first constructor for ApplyA?
This should be possible with higher-order polymorphism, but I could not work out how. I know that I can do this even without using higher-order polymorphism by simply wrapping constructors in functions and then passing these functions as first argument to the constructor for ApplyA, but I’d like to understand how to use higher-order polymorphism directly.
The problem is that the
Listexample doesn’t involve any higher-order polymorphism at all.List.applyjust takes a variable number of parameters:Higher-order polymorphism involves methods, or types, which take type constructors as type parameters, e.g.
So no, you can’t do it using higher-order polymorphism.