Functors in Scala

Following on my earlier entry on modules in Scala, I'll give an encoding of Standard ML style functors here. You can get a pretty close approximation by using class constructor arguments. However, I am going to cheat a little to get the closest encoding I think is possible by using the experimental support for dependent method types. You can get this by running scala or scalac with the option -Xexperimental. It works okay at least some of the time, but no one has the time at the moment to commit to getting it in shape for general consumption.

So here is my example of how the encoding works. First, the SML version:

  1.  
  2. signature Eq = sig
  3. type t
  4. val eq: t -> t -> bool
  5. end
  6.  
  7. signature RicherEq = sig
  8. include Eq
  9. val neq: t -> t -> bool
  10. end
  11.  
  12. functor mkRicherEq(arg : Eq) :> RicherEq where type t = arg.t = struct
  13. type t = arg.t
  14. val eq = arg.eq
  15. fun neq x y = not (eq x y)
  16. end
  17.  

We can transliterate this example into Scala as:

  1.  
  2. type Eq = {
  3. type T
  4. def eq(x: T, y: T): Boolean
  5. }
  6.  
  7. type RicherEq = {
  8. type T
  9. def eq(x: T, y: T): Boolean
  10. def neq(x: T, y: T): Boolean
  11. }
  12.  
  13. def mkRicherEq(arg: Eq) : RicherEq { type T = arg.T } = new {
  14. type T = arg.T
  15. def eq(x: T, y: T) = arg.eq(x, y)
  16. def neq(x: T, y:T) = !eq(x, y)
  17. }
  18.  

The only problem I discovered is that it is not possible to define RicherEq in terms of Eq as we could in SML:

  1.  
  2. scala> type RicherEq = Eq { def neq(x: T, y: T): Boolean }
  3. <console>:5: error: Parameter type in structural refinement may
  4. not refer to abstract type defined outside that same refinement
  5. type RicherEq = Eq { def neq(x: T, y: T): Boolean }
  6. ^
  7. <console>:5: error: Parameter type in structural refinement may
  8. not refer to abstract type defined outside that same refinement
  9. type RicherEq = Eq { def neq(x: T, y: T): Boolean }
  10. ^
  11.  

Why this restriction exists I don't know. In fact, this sort of refinement should work in the current version of Featherweight Scala, so perhaps it can be lifted eventually.

I still need to think about higher-order functors, and probably spend a few minutes researching existing proposals. I think this is probably something that cannot be easily supported in Scala if it will require allowing method invocations to appear in paths. However, off hand that only seems like it should be necessary for applicative higher-order functors, but again I definitely need to think it through.

Comments (2)