Seite 1 von 1

Environments as Scala Functions: Problem with recBind

Verfasst: 2. Mär 2018 11:35
von Jannis
Hi!

On slide 81 of V05-FirstClassFunctions, it is asked whether there are any problems with the following definition of recBind:

Code: Alles auswählen

def recBind(boundId: Symbol, namedExpr: Expr, env: Env): Env = {
    def recEnv: Env = { id =>
        if (id == boundId) interp(namedExpr, recEnv)
        else env(id)
    }
    recEnv
}
If I remember correctly, we said that this definition does not work because Scala does eager evaluation. Therefore we would have to add the lazy keyword as seen in RCFLAEFunEnvsInterp.scala:

Code: Alles auswählen

def cycBindAndInterp(boundId: Symbol, namedExpr: RCFLAE, env: Env): Env = {
    lazy val recEnv: Env = (id: Symbol) => {
        if (id == boundId) interp(namedExpr, recEnv)
        else env(id)
    }
    recEnv
}
But is this actually needed? Scala does not directly evaluate functions when you pass them around. So I guess using def should actually work, too.

Re: Environments as Scala Functions: Problem with recBind

Verfasst: 2. Mär 2018 17:59
von mirko-koehler
I don't know what was said in the lecture, and maybe I'm missing something, but the code works with def and with lazy val. With val, however, it does not work because you refer to recEnv in the definition of recEnv.