I’m very new to Scala, and while reading the ScalaTutorial.pdf Section 6: Case classes and pattern matching
I find no information on how to run its example which is:
package my
abstract class Tree
case class Sum(l: Tree, r: Tree) extends Tree
case class Var(n: String) extends Tree
case class Const(i: Int) extends Tree
object TestTree {
type Environment = String => Int
def eval(t: Tree, env: Environment): Int = t match {
case Sum(l, r) => eval(l, env) + eval(r, env)
case Var(n) => env(n)
case Const(v) => v
}
def main(args: Array[String]){
val s : Sum = Sum(Var("x"), Const(10))
// Then how to define a variable of type environment to pass it to the `eval` function:
//eval(s, Environment) ??
}
}
I don’t know how to pass the Environment to the eval function
This says that the type
Environmentis equal to the typeString => Int, i.e. the type of functions that take aStringand return anInt. It should be noted that in Scala a map is a kind of function (which is to sayMap[K,V]is a subtype ofK => V). So any function that takes a function as an argument can also take a map instead.So to use
evalyou can pass it a function of typeString => Int, which might either be an actual function that you defined and that takes a string and returns an int, or a map that maps strings to integers.