It turns out that my previous Scala idea to model environments for arithmetic expressions doesn’t fly. Solution? Go to the Scala mailing list and ask for opinions, there is always a lot of helpful, highly skilled people willing to help. What follows is my account of things based on the help that I have got.
My initial solution was to create a type like this:
type Env = String => Double
Doesn’t work as types have to be defined inside objects or classes. This will, by the way, work on the interpreter as the interpreter is really running inside an anonymous class (so type definitions will be attached to that anonymous class).
I then tried 2 traits as alternatives:
trait Env {
def apply(name : String) : Double
}and
trait Env extends Fuction1[String, Double]
When I used any of those like in:
val env : Env = (x : String) => x match {case "S" => 1.0}I had a typing error complaining that String => Double is different from Env. But is it really? Aren’t the two traits above the same as String => Double? Well, they are, but Scala uses nominative typing, not structural typing. So after you give that type a name it will be different from equal structural types that have different names.
I ended up with with a type inside a companion object. The companion object pattern seems to be widely used in Scala. I still don’t have a opinion if that is generally good or bad.
In any case, I don’t like the idea that types cannot be defined top level. I don’t see any advantage in disallowing this.
Please share your thoughts
Filed in: Scala










