使用模式匹配求解 scala 中的某些方程
我对 Scala 非常陌生,在阅读 ScalaTutorial.pdf 时第 6 节:案例类和模式匹配
我没有找到有关如何运行其示例的信息,即:
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) ??
}
}
我不知道如何将环境传递给 eval
函数
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这表示
Environment
类型等于String => 类型。 Int
,即采用String
并返回Int
的函数类型。需要注意的是,在 Scala 中,map 是一种函数(也就是说Map[K,V]
是K => V
的子类型)。因此,任何采用函数作为参数的函数也可以采用映射。因此,要使用
eval
,您可以向其传递String => 类型的函数。 Int
,它可能是您定义的实际函数,它接受一个字符串并返回一个 int,也可能是一个将字符串映射到整数的映射。This says that the type
Environment
is equal to the typeString => Int
, i.e. the type of functions that take aString
and 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
eval
you 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.