## Assignment 12.2 SetId

christoph_l
Neuling
Beiträge: 2
Registriert: 20. Okt 2016 20:13

### Assignment 12.2 SetId

Hello,

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

Regards, Christoph

Sylvia G.
Mausschubser
Beiträge: 73
Registriert: 22. Sep 2007 14:30

### Re: Assignment 12.2 SetId

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...?

GS-812
Windoof-User
Beiträge: 30
Registriert: 25. Apr 2015 12:47

### Re: Assignment 12.2 SetId

Hi,

in the Weblap I got th following answer:

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
ctx.put(id,newType)
newType
}
else
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?

Best ragards
Georg

Ragnar
Mausschubser
Beiträge: 63
Registriert: 21. Okt 2009 19:15

### Re: Assignment 12.2 SetId

Hi,

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.