Seite 1 von 1

Assignment 12.2 SetId

Verfasst: 3. Feb 2017 11:25
von christoph_l

the type of the value of a box may not change. May the type of an id change?

Regards, Christoph

Re: Assignment 12.2 SetId

Verfasst: 3. Feb 2017 11:45
von Sylvia G.
To answer this question, you should think about whether you can come up with example expressions that your type system would accept if you allowed the type of an id to change, but that would fail during interpretation.

What happens for example if you define a function in an inner let that in the body uses the id of the outer let in a certain way...?

Since we are not alone here in the forum, who can come up with a nice (counter)example in that direction...?

Your turn ;).

Re: Assignment 12.2 SetId

Verfasst: 1. Mär 2017 13:22
von GS-812

in the Weblap I got th following answer:

Grading Comments:
Your SetId case doesn't check if the new value type fits the id's original type.

Now I tried to implement this.

Code: Alles auswählen

     case SetId(id, valueExpr) => {
      val newType = typeOf(valueExpr,ctx)
      val oldType = ctx.getOrElse(id,newType)

      if(oldType == newType){
        // StoreVariable
        sys.error("ID should change it's type is forbitten")
This code is working, but I must refactored

Code: Alles auswählen

type Ctx = scala.collection.mutable.Map[Symbol, Type]
to a mutable Map to be able to insert/store seen types of id.

What would be the solution?
Let "ctx.put(id,newType)" out, so external functions must insert the id-types ?

Or should I change Ctx to a mutable Map?

Thanks in Advance

Best ragards

Re: Assignment 12.2 SetId

Verfasst: 1. Mär 2017 19:34
von Ragnar

typing contexts, like environments, do not change, you just add bindings from names to types (which may shadow older bindings).
Especially the SetId case should only do a lookup in the context, to see whether storing a value of the given type can be stored in the location where you want to store to.
code example:

Code: Alles auswählen

var x: Int = 3 //Let Case
x = 10 // SetId Case
x = "test" //SetId Case
In the first line, the typechecker records, that x is of type Int for the rest of the scope (until the end of the example)
the only thing the typechecker does in the second line is to check whether a value of type Int can be stored in the variable named `x`. The answer is yes, and in our language, the resulting type will also be Int. (In Scala the result type is actually Unit, because that is how assignments are defined.)
In the third line the types are different, so the typechecker will complain.