First Class Functions
@PL on
We are defining FVAE
, arithmetic expressions with first class functions. In this language, functions are first class object; they can be passed as an argument, modified, returned or assigned to a variable.
FVAE
adds two new rules to expression. Let’s define Fun
to make a closure, and App
for function application.
enum Expr: prevExpr {
// includes all the former definition
case Fun(String, Expr) //fcf
case App(Expr, Expr) //fcf
}
We also need a new type of value, CloV
to express the function as a value.
enum Value: oldValue {
case CloV(String, Expr, Env) //fcf
}
Interpretation implementation.
func interp(_ e: Expr, _ env: Env) -> Value
{
switch e {
case .Num(let n):
return .NumV(n)
case .Add(let l, let r):
return NumVOperation(ADD, interp(l, env), interp(r, env))
case .Sub(let l, let r):
return NumVOperation(SUB, interp(l, env), interp(r, env))
case .Val(let x, let i, let b):
return interp(b, env + [x : interp(i, env)])
case .Id(let x):
return env[x]!
case .Fun(let x, let b):
return .CloV(x, b, env)
case .App(let f, let a):
switch interp(f, env) {
case .CloV(let x, let b, let fenv):
return interp(b, fenv + [x : interp(a, env)])
default:
exit(1) //error: Not closure!
}
}
}
print(interp(.Val("x", .Num(5), .Val("f", .Fun("y", .Add(.Id("x"), .Id("y"))),
.App(.Fun("g", .App(.Id("f"), .App(.Id("g"), .Num(1)))),.Fun("x", .Id("x"))))),Env())) //NumV(6)
All the materials are from CS320 class held on 2021 spring, KAIST.