Discord is now Scala’s main chat platform. Please join us at https://discord.com/invite/scala
"x".->(2)
Map
is a common technique to implement environments for closures when doing e.g. an interpreter :)
sealed trait AssignmentTo
case class Constant(c: Int) extends AssignmentTo
case class Variable(varName: String) extends AssignmentTo
Seq[(String, AssignmentTo)](
"x" -> Constant(1),
"y" -> Constant(2),
"z" -> Constant(3),
"uhoh" -> Variable("x"),
"x" -> Constant(1),
"uhoh" -> Variable("x")
).foldLeft(Map.empty[String, Int]) { case (acc, (ident, assign)) =>
val newValue = assign match {
case Constant(c) => c
case Variable(varName) => acc(varName)
}
acc + ((ident, newValue))
}
98 + 1 = 100
"
"x"
to 1
val x = 12345
. Your interpreted language is the language with the primitives defined asAssignmentTo
, interpreted by the function in the fold -- only when you give AssignmentTo
the meaning of being a program, then the mutability shows up.