## RCFAE Interpreter

prabhjot
Erstie
Beiträge: 11
Registriert: 5. Aug 2016 16:30

### RCFAE Interpreter

Code: Alles auswählen

case Rec(boundId, namedExpr, boundBody) => {
val recEnv = collection.mutable.Map() ++ env
recEnv += boundId -> interp(namedExpr, recEnv)
interp(boundBody, recEnv)
}

what is the use of adding an empty map to env which is already a Map ?

I think, I understood the idea behind the implementation, but I cannot understand that with this piece of code. To me it does not look much different than

Code: Alles auswählen

env + (boundId -> interp(namedExpr, env))
What am I missing ??

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

### Re: RCFAE Interpreter

The first line:

Code: Alles auswählen

val recEnv = collection.mutable.Map() ++ env

has the result, that recEnv is a mutable map, which contains all elements from env. This is important, so that mutating recEnv does not change env.
The second line is a bit tricky, because it uses and modifies the same map in a single statement, so here evaluation order is very important.

Code: Alles auswählen

recEnv += boundId -> interp(namedExpr, recEnv)

let me make the evaluation order a bit more explicit, this will behave exactly as the line before:

Code: Alles auswählen

val recursiveBoundValue = interp(namedExpr, recEnv)
recEnv += boundId -> recursiveBoundValue

what you can see here, is that we evaluate the namedExpr in the recEnv.
Because this is a recursive definition, namedExpr may contain references to the boundId, but boundId is not yet in the recEnv, because we only know the recursiveBoundValue after the evaluation.
So we evaluate namedExpr in the recEnv and require that the boundId is not immediately used (which would result in infinite recursion anyways), but only used guarded inside a closure.
Afterwards we fix recEnv by putting the correct value at boundId. And because this is a mutable map, this change will also be visible everywhere recEnv was used (captured by a closure) inside of namedExpr.

prabhjot
Erstie
Beiträge: 11
Registriert: 5. Aug 2016 16:30

### Re: RCFAE Interpreter

Thanks for explaining, it is clear now.

I missed this -
So we evaluate namedExpr in the recEnv and require that the boundId is not immediately used (which would result in infinite recursion anyways), but only used guarded inside a closure.